有没有办法做到这一点?我有一个输出一篇博客文章的模板.
现在,在索引页面上我通过在for循环中包含该模板来显示10篇文章,并且在显示页面上我只显示一个.
指数:
{% block stylesheets %}
{# some stylesheets here #}
{% endblock %}
{% for article in articles %}
{% include VendorBundle:article.html.twig with { 'article': article } %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
节目:
{% block stylesheets %}
{# some stylesheets here #}
{% endblock %}
{% include VendorBundle:article.html.twig with { 'article': article } %}
Run Code Online (Sandbox Code Playgroud)
现在有没有办法让article.html.twig自动添加{% block stylesheets %}包含它的模板?如果可能,如何在使用for循环时阻止它添加10次?
我正在尝试使我的"片段"模板(用于包含的模板)定义他们使用的样式表,并使它们"注入"到页面中.
Sir*_*ton 18
你尝试过用吗?不幸的是,我不能完全确定我是否正确地提出了问题,但{% use %}这里没有提到.
据我所知,你已经得到了你的问题article.html.twig并将其包含在例如index.html.twig.现在,你想从添加的东西article.html.twig到index.html.twig?即到{% stylesheets %}街区.
如果我有如何使用{% use %}你可以尝试这样.
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 %}
Run Code Online (Sandbox Code Playgroud)
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 %}
Run Code Online (Sandbox Code Playgroud)
我没有机会测试它,但是文档中列出了一些非常有趣的东西,看起来这可能就是这样做的方法.
水平重用是一种先进的Twig功能,在常规模板中几乎不需要.它主要由需要使模板块可重用而不使用继承的项目使用.
我对stackoverflow很新.所以,如果我的答案完全没用,请你在投票前发表评论并删除它吗?但是,如果它确实有帮助,并且我的示例中只有一些错误,也请通知我,我会解决它.
您可以使用新块(未测试):
{# index.html.twig #}
{% block stylesheets -%}
{% block article_styles '' %}
{%- endblock %}
{% for ... -%}
{% include VendorBundle:template.html.twig with {'article': article} %}
{%- endfor %}
Run Code Online (Sandbox Code Playgroud)
{# template.html.twig #}
{% block article_styles -%}
{{ parent() }}
<link rel=stylesheet href=...>
{%- endblock %}
{# ... #}
Run Code Online (Sandbox Code Playgroud)
编辑:添加{{ parent() }},这将打印块已有的所有内容。
| 归档时间: |
|
| 查看次数: |
11017 次 |
| 最近记录: |