2016-09-23 76 views
2

我一直在寻找这方面的互联网,但我找不到任何关于此的东西。Symfony/Twig:停止渲染模板的其余部分

我正在创建一个简单的树枝模板,它将用于多个位置,但需要一些变量。

我希望能够做这样的事情:

{% if some_variable is not defined %} 
    <h1>Some variable was not defined.<h1> 
    -- stop rendering the rest of the template -- 
{% endif %} 

{{ some_variable }} is defined here. 

我问这个的原因是非常简单的。 我不希望我的整个模板在一个或多个if-表达式中缩进,因为它会使整个文件非常容易混乱。

我知道解决方法是创建多个模板,但对于一个简单的条件多个文件听起来有点矫枉过正。

如果这本不存在,我可以为此创建扩展,如果任何人都可以告诉我如何以及如果这可以实现。

在此先感谢!

P.S.不要回答{% else %},这正是我想要避免在这里...

+0

您可以创建你自己的扩展和impl php'die'功能 – Matteo

+0

这将停止整个应用程序的执行。对不起,这绝对不是我想要的;) – Harold

回答

2

你要求的是不是本机支持。
要实现这样的事情,你需要经历很多麻烦。

Twig模板被编译到PHP中,由Twig自己的基本模板扩展。在基本模板中查看时,您会看到最终将调用功能doDisplay。该功能的内容示例如下

protected function doDisplay(array $context, array $blocks = array()) 
    { 
     // line 1 
     echo "\t<div id=\"null_wrapper\"> 
\t\t<div class=\"invoice_price\">\t\t\t 
\t\t\t<div> 
\t\t\t\t"; 
     // line 4 
     echo twig_escape_filter($this->env, $this->getAttribute((isset($context["forms"]) ? $context["forms"] : $this->getContext($context, "forms")), "getTextfield", array(0 => "#label_Quantity#", 1 => "txt_new_quantity", 2 => ((array_key_exists("txt_quantity", $context)) ? (_twig_default_filter((isset($context["txt_quantity"]) ? $context["txt_quantity"] : $this->getContext($context, "txt_quantity")), 1)) : (1)), 3 => ((array_key_exists("errors", $context)) ? (_twig_default_filter((isset($context["errors"]) ? $context["errors"] : $this->getContext($context, "errors")), "")) : ("")), 4 => "", 5 => "smallinput"), "method"), "html", null, true); 
     echo " 
\t\t\t</div> 
\t\t\t<div class=\"clear\"></div> 
\t\t\t<div> 
\t\t\t\t"; 
     // line 8 
     echo twig_escape_filter($this->env, $this->getAttribute((isset($context["forms"]) ? $context["forms"] : $this->getContext($context, "forms")), "getTextfield", array(0 => "#label_Unit_price#", 1 => "txt_new_price_excl", 2 => ((array_key_exists("txt_new_price_excl", $context)) ? (_twig_default_filter((isset($context["txt_new_price_excl"]) ? $context["txt_new_price_excl"] : $this->getContext($context, "txt_new_price_excl")), "")) : ("")), 3 => ((array_key_exists("errors", $context)) ? (_twig_default_filter((isset($context["errors"]) ? $context["errors"] : $this->getContext($context, "errors")), "")) : ("")), 4 => "", 5 => "smallinput"), "method"), "html", null, true); 
     echo "<span>"; 
     echo twig_escape_filter($this->env, getSiteConfigValue("CURRENCY"), "html", null, true); 
     echo "</span> 
\t\t\t</div> 
\t\t\t<div class=\"clear\"></div> 
\t\t\t<div> 
\t\t\t\t"; 

正如你所看到的输出(在基本模板和逮住由ob_start)立即发送到浏览器,所以即使你可以退出一个模板出来机会存在,你会最终破碎的HTML。

TL:DR实现这样的事情的唯一方法是重写的twig的编译器,编译twig模板为PHP,或许你可以写你自己的节点,因为这使/编译以及

+0

感谢您的快速回复,DarkBee.Guess我会解决的解决方法,然后。不幸的是,这确实听起来像更多的麻烦。 – Harold