将样式从twig include移动到父模板中

时间:2017-01-19 09:25:46

标签: templates twig symfony

我正在开发一个包含数百个twig模板的相对较大的应用程序。考虑以下简化结构:

{# layout.html.twig #}
<!DOCTYPE html>
<html>
  <head>
    {% block head %}{% endblock %}
  </head>
  <body>
      {% block body %}{% endblock %}
  </body>
</html>

_

{# view.html.twig #}
{% extends 'layout.html.twig' %}

{% block head %}
    {# this will go into the head of the document and works fine #}
{% endblock %}

{% block body %}
    {% include 'include.html.twig' %}
{% endblock %}

_

{# include.html.twig #}
<style>
  /* 
    I want this style block appear in the head of the document (layout.html.twig).
    Using {% block head %} is not an option, as this code is evaluated later than the head block is flushed
  */
  {{ generate_minified_css_here() }}
</style>

<!-- rest of included content -->

我想确保每当我include一个模板时,也会包含样式。由于样式和模板的数量,不能生成一个大的css文件。

在过去,我通过使用scoped样式标签来处理这个问题,并且所有这些都经过了完美的验证,即使样式实际上并没有&#34;作用范围&#34;大多数浏览器。从最近开始,W3C不再接受范围样式。

我的问题是:如何将include.html.twig的样式转换为layout.html.twig头部?

1 个答案:

答案 0 :(得分:0)

那么分割你的SubscriptionController@update模板并获得这种结构怎么样?:

include.html

-

{% block head %}
    {% include 'include-style.html.twig' %}
{% endblock %}

{% block body %}
    {% include 'include.html.twig' %}
{% endblock %}

-

{# include-style.html.twig #}
<style>
  /* 
    I want this style block appear in the head of the document (layout.html.twig).
    Using {% block head %} is not an option, as this code is evaluated later than the head block is flushed
  */
  {{ generate_minified_css_here() }}
</style>