Symfony 我可以在TWIG中使用变量吗?
我使用symfony2和TWIG,我想使用一些全局变量来指向页面中平板电脑的索引: app/config/parameters.iniSymfony 我可以在TWIG中使用变量吗?,symfony,twig,Symfony,Twig,我使用symfony2和TWIG,我想使用一些全局变量来指向页面中平板电脑的索引: app/config/parameters.ini tab_branch=“1” app/config/config.yml twig: globals: tab_branch: %tab_branch% src/ACME/BranchBundle/Controller/defaultController.php /** *@Template() */ 公共功能展示($id){ ...
tab_branch=“1”
app/config/config.yml
twig:
globals:
tab_branch: %tab_branch%
src/ACME/BranchBundle/Controller/defaultController.php
/**
*@Template()
*/
公共功能展示($id){
...
返回数组(
“tab'=>“tab_分支”,
);
}
src/ACME/BranchBundle/Resources/views/default/show.html.twig
//不工作
我真正想做的是将
{{tab}}
解析为tab\u branch
,然后{{tab\u branch}
解析为1
(就像PHP中的$$foo
),我应该怎么做?这不能按照您尝试的方式来做,twig不是那样工作的。如果tab的可能值不多,可以执行以下操作:
{% if tab == 'tab_branch' %}
{{tab_branch}}
{% else if tab == 'other_tab' %}
{{other_tab}}
{% endif %}
我知道,不是很优雅…编写一个自定义函数来允许这种计算
您可能对本提案感兴趣我使用twig语法在我的数据中的任何位置引用其他变量:
foo: "{{ bar.baz }}/quu.txt"
bar:
baz: /tmp
然后渲染,直到结果不再更改:
while( $template !== ($result = $twig->render($template, $data)) )
{
$template = $result;
}
这是
- 不美观:每个变量值都应该在嵌入之前呈现
- 不足:变量名在使用前未呈现,因此foo.{{i}}不起作用
- 简单:我不需要引用过滤器或代码,只需要引用变量
- 小:上面的实现很短,希望很清楚。也可以是单行递归方法
{app.request.attributes.get(“'u route')=='FooBar'?'foo':'bar'}
)或者选择更复杂的东西,比如使用。