Hap*_*per 5 javascript templates symfony twig
我想创建可以自己打印一些HTML代码的视图,同时将javascript代码发送到底部,而不扩展布局
我的想法是我有一个布局,然后当前网址的特定视图扩展了该布局,在该视图中,我包含了其他视图,这些视图可以将代码添加到超出范围的其他块(因为它们不在不继承自布局或从中继承的视图.那可能吗?
假设这是我布局的一部分:
{# ::layout.html.twig #}
.
.
{% block javascripts %}
{% endblock %}
</body>
.
.
Run Code Online (Sandbox Code Playgroud)
这是我的看法:
{# Company:Bundle:about.html.twig #}
{% extends '::layout.html.twig' %}
.
.
{% include 'Company:buttons:google_button.html.twig' %}
.
.
Run Code Online (Sandbox Code Playgroud)
这是我想要包含的视图,例如,谷歌+1按钮:
{# Company:buttons:google_button.html.twig #}
<gb></gb> {# or whatever #}
{# somehow send '<script>blabla</script>' to the 'javascripts' block #}
Run Code Online (Sandbox Code Playgroud)
是否可以用twig和symfony2做这样的事情?
我想你必须编写自己的 Twig 扩展来定义两个函数,比如说add_js和print_js。
树枝扩展:
namespace Me\MyBundle\Twig\Extension;
class MyExtension extends \Twig_Extension {
private $js = array();
/**
* {@inheritdoc}
*/
public function getFunctions() {
return array(
'put_js' => new \Twig_Function_Method($this, 'putJs', array('is_safe' => array('html'))),
'print_js' => new \Twig_Function_Method($this, 'printJs', array('is_safe' => array('html')))
);
}
public function putJs($js) {
$this->js[] = $js;
}
public function printJs() {
return implode(PHP_EOL, $this->js);
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName() {
return 'my';
}
}
Run Code Online (Sandbox Code Playgroud)
依赖注入配置:
<service id="twig.extension.me.my" class="Me\MyBundle\Twig\Extension\MyExtension" public="false">
<tag name="twig.extension" />
</service>
Run Code Online (Sandbox Code Playgroud)
最终用途:
{# ::layout.html.twig #}
...
{{ print_js() }}
</body>
{# Company:buttons:google_button.html.twig #}
{% put_js('<script>...</script>') %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1767 次 |
| 最近记录: |