我有这个
base.html.twig
<html>
{% block template_scope_vars %}
{% endblock %}
<head></head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
user.html.twig
extends base...
{%block template_scope_vars %}
{% set test= "bippo" %}
{%endblock%}
{%block content %}
{{ test }}
{% endblock %}
错误
变量“test”不存在
好的请不要告诉我,我没有必要使用块,用例比这个简单的例子显然更难。我的想法是test
中也可以使用base.html.twig
,以及我将来可能使用的任何子模板
答案 0 :(得分:0)
对于我可以使用的特殊用例。遗憾的是,没有更简洁的解决方案。我能提出的所有其他解决方案都需要为每组模板范围变量创建一个新文件。哪个简单糟透了
<强> base.html.twig 强>
<div id="menu"> //this is like a sidebar menu
<div class="menuitem {% block foo %}{% endblock %}">
<a href="{{ path('MyBundle_my_routing_name_foo' }}">Foo</a>
</div>
<div class="menuitem {% block bar %}{% endblock %}">
<a href="{{ path('MyBundle_my_routing_name_bar' }}">Bar</a>
</div>
<div>
{% block content %}
{% endblock %}
然后在
<强> foo.html.twig 强>
{% extends "MyBundle::base.html.twig" %}
{% block foo %}active{% endblock %}
{% block content %}
Some content specific for foo
{% endblock %}
<强> bar.html.twig 强>
{% extends "MyBundle::base.html.twig" %}
{% block bar%}active{% endblock %}
{% block content %}
Some content specific for bar
{% endblock %}
然后将css设置为例如
的背景CSS
menuitem.active {
background-color: red;
}
答案 1 :(得分:0)
<强> base.html.twig 强>
<div id="menu"> //this is like a sidebar menu
<div class="menuitem{{ active == 'foo' ? ' active' : '' }}">
<a href="{{ path('MyBundle_my_routing_name_foo') }}">Foo</a>
</div>
<div class="menuitem{{ active == 'bar' ? ' active' : '' }}">
<a href="{{ path('MyBundle_my_routing_name_bar') }}">Bar</a>
</div>
<div>
{% block content %}
{% endblock %}
<强> foo.html.twig 强>
{% extends "MyBundle:Whatever:base.html.twig" %}
{% block content %}
{{ content }}
{% endblock %}
<强>控制器强>
/**
* @Route("/foo", defaults={"param" = null}, name="foo")
* @Route("/foo/{param}", name="foo_with_param")
* @Template()
*/
public function fooAction($param)
{
// This would really be getting data from the Model
if ($param == 'something') {
$content = 'Some content';
$active = 'foo';
} else {
$content = 'Different content';
$active = 'bar';
}
return array(
'content'=> $content,
'active' => $active,
);
}
渲染foo.html.twig时,base.html.twig将获取变量&#34; active&#34;。