Twig 在细枝中呈现HTML标题元素

Twig 在细枝中呈现HTML标题元素,twig,html-heading,Twig,Html Heading,我正在使用twig呈现一些标题,想知道是否有更好、更具可读性的方法来执行以下操作 <{{ block.headingType }} class="measure-wide">{{ block.headingText }}</{{ block.headingType }}> {{block.headingText} {{block.headingType}}是在编辑器中选择的标题的值。数值为h2、h3、h4、h5等 HTML标题模板化的方式看起来很难看(即使渲染工作正常

我正在使用twig呈现一些标题,想知道是否有更好、更具可读性的方法来执行以下操作

<{{ block.headingType }} class="measure-wide">{{ block.headingText }}</{{ block.headingType }}>
{{block.headingText}
{{block.headingType}}是在编辑器中选择的标题的值。数值为h2、h3、h4、h5等


HTML标题模板化的方式看起来很难看(即使渲染工作正常)。有没有更好的方法可以根据所选的值在twig中呈现标题标记?

如果您使用了大量标题,我建议创建一个类来处理这个问题,并添加一个
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;
    }
}

在你的
-类中引入一个
\uuuu toString
方法,你就可以做
{{block|raw}}
你能在下面的回答中给我一个例子吗?
<?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> #}
{{ heading1.getHtml() }} {# out: <h1>Title</h1> #}