Twig included template extending parent#39;s block once(Twig 包含扩展父块一次的模板)
问题描述
Is there a way to do this? I have a template which outputs one blog article.
Now, on index page I show 10 articles by including that template in for loop and on show page I only show one.
index:
{% block stylesheets %}
{# some stylesheets here #}
{% endblock %}
{% for article in articles %}
{% include VendorBundle:article.html.twig with { 'article': article } %}
{% endfor %}
show:
{% block stylesheets %}
{# some stylesheets here #}
{% endblock %}
{% include VendorBundle:article.html.twig with { 'article': article } %}
Now is there a way to make article.html.twig add something to {% block stylesheets %}
of templates that included it automatically? If it is possible, how do I prevent it from adding that 10 times when using for
loop?
I'm trying to make my "fragment" templates (templates used for inclusion) define stylesheets that they use and make them "inject" those into page.
Did you try to use use?
Unfortunately I'm not completely sure if I got the question right but {% use %}
wasn't mentioned here.
As I understand the question you've got your article.html.twig
and include it in e.g. index.html.twig
. Now you want to add something from article.html.twig
into index.html.twig
? Namely to the {% stylesheets %}
block.
If I got how to use {% use %}
you could maybe try it like this.
article.html.twig
{% block stylesheets %}
<link rel="stylesheet" href="{{ asset('bundles/mybundle/css/article.css') }}" type="text/css" />
{% endblock %}
{% block article %}
{# whatever you do here #}
{% endblock %}
index.html.twig
{% use "VendorBundle:article.html.twig" with stylesheets as article_styles %}
{% block stylesheets %}
{{ block('article_styles') }}
{# other styles here #}
{% endblock %}
{% for article in articles %}
{% include VendorBundle:article.html.twig with { 'article': article } %}
{% endfor %}
I have not the chance to test it but the docu states a few very interesting things and it seems like this could be the way to do it.
Horizontal reuse is an advanced Twig feature that is hardly ever needed in regular templates. It is mainly used by projects that need to make template blocks reusable without using inheritance.
I am rather new to stackoverflow. So please if my answer is completely useless could you just post a comment before down voting and I delete it? However if it does help and there are just some errors in my example, also inform me and I'll fix it.
这篇关于Twig 包含扩展父块一次的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Twig 包含扩展父块一次的模板
基础教程推荐
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01