Is it possible in twig to get the name of the child template in the layout? For Ex开发者_如何学Pythonample when calling:
$app['twig']->render('index.twig');
then in layout.twig, which is the main layout, it should ask:
if page is index.twig => include this javascript
I could do this with additional variables in the render call, but this seems to be bloated since the template name would indicate it already.
You are looking at this the wrong way. Imagine if you had a lot of views, then you'd have to do that for each one:
{% if _self.getTemplateName() == 'index.twig' %}
<script src="{{ asset('somescript1') }}"></script>
{% endif %}
{% if _self.getTemplateName() == 'members.twig' %}
<script src="{{ asset('somescript2') }}"></script>
{% endif %}
{% if _self.getTemplateName() == 'news.twig' %}
<script src="{{ asset('somescript3') }}"></script>
{% endif %}
...
I find this approach pretty bad. What you can do, in your main layout file (lets assume its 'layout.html.twig' for this example) is make a block:
{% block javascripts %}
{% endblock %}
Then, in your view files:
{% extends 'AcmeHelloBundle::layout.html.twig' %}
....
{% block javascripts %}
<script src="asset('index.js')"></script>
{% endblock %}
Basically, you're overriding the block inside your layout file with new contents. In case you had anything inside your 'layout.html.twig' (like for example jquery), you'd also have to call parent():
{% extends 'AcmeHelloBundle::layout.html.twig' %}
....
{% block javascripts %}
{{ parent() }}
<script src="asset('index.js')"></script>
{% endblock %}
parent()
just makes sure to copy all of the contents from the parent block too.
精彩评论