【问题标题】:Rendering HTML Heading Elements in Twig在 Twig 中呈现 HTML 标题元素
【发布时间】:2018-12-04 14:30:33
【问题描述】:

我正在使用 twig 渲染一些标题,并想知道是否有更好、更易读的方法来执行以下操作...

<{{ block.headingType }} class="measure-wide">{{ block.headingText }}</{{ block.headingType }}>

{{ block.headingType }} 是编辑器中选择的标题的值。值为 h2、h3、h4、h5 等。

HTML 标题的模板化方式看起来很难看(即使渲染工作正常)。有没有更好的方法根据选择的值渲染出树枝中的标题标签?

【问题讨论】:

  • 在你的block-class 中引入一个__toString 方法,你可以这样做{{ block | raw }}
  • 你能在下面的回复中给我一个例子吗?

标签: twig html-heading


【解决方案1】:

如果您使用大量标头,我建议您创建一个类来处理此问题并添加一个toString 方法,这样可以更轻松地呈现标签

class Heading {

    private $heading_type = 'h1';
    private $heading_text;
    private $classes = [];

    public function __construct($text) {
        $this->setHeadingText($text);
    }

    public function addClass($c) {
        if (!in_array($c, $this->classes)) $this->classes[] = $c;
        return $this;
    }

    public function getHtml() {
        return new \Twig_Markup($this->__toString(), 'UTF-8');
    }

    public function __toString() {
        return '<'.$this->getHeadingType().(!empty($this->getClasses()) ? ' class="'.implode(' ',$this->getClasses()).'"':'').'>'.$this->getHeadingText().'</'.$this->getHeadingType().'>';
    }

/**============================================
                GETTERS/SETTERS
============================================**/
    public function setHeadingType($value) {
        $this->heading_type = $value;
        return $this;
    }

    public function getHeadingType() {
        return $this->heading_type;
    }

    public function setHeadingText($value) {
        $this->heading_text = $value;
        return $this;
    }

    public function getHeadingText() {
        return $this->heading_text;
    }

    public function getClasses() {
        return $this->classes;
    }
}

<?php
    $twig->render('template.twig', [
        'heading1' => new Heading('Title'),
        'heading2' => (new Heading('Subtitle'))->setHeadingType('h2')
                                               ->addClass('foo'),
    ]);

{{ heading1 | raw }} {# out: <h1>Title</h1> #}
{{ heading2 | raw }} {# out: <h2 class="foo">Subtitle</h2> #}

编辑:添加了一个 getHtml,它允许您删除原始过滤器,例如

{{ heading1.getHtml() }} {# out: <h1>Title</h1> #}

【讨论】:

    猜你喜欢
    • 2016-08-10
    • 1970-01-01
    • 2020-04-11
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    相关资源
    最近更新 更多