2017-01-19 2 views
0

私は、数百の小枝テンプレートを含む比較的大きなアプリで作業しています。以下の構造の簡素化を検討:小枝から親テンプレートにスタイルを移動する

{# 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 %} 

_私はそのI includeテンプレート、スタイルが含まれているときは常にだけでなく確認する

{# 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 --> 

。スタイルとテンプレートの量のために、1つの大きなCSSファイルを生成することはオプションではありません。

これまではscopedスタイルタグを使用してこれを処理していましたが、スタイルは実際にはほとんどのブラウザで「スコープ」になっていませんが、すべてが完全に検証されていました。最近、W3Cはスコープ付きスタイルを受け入れなくなりました。

私の質問は:include.html.twigからlayout.html.twigヘッドセクションにスタイルを取得するにはどうすればよいですか?

+0

をあなたは '含めることはできません.html.twig' *はlayout.html.twigを操作します。インクルードされたファイルは文字列としてインクルードされるからです。つまり、インクルードされたテンプレートが完全に最初にレンダリングされ、結果がインクルードファイルに配置されることを意味します。 – Yoshi

答えて

0

そして、何についてのあなたの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> 

- あなたの現在の設定では

{# include.html.twig #}  
<!-- included content without style content --> 
+0

'include.html.twig'を分割することができました。問題は、ビュー本体内に複雑なロジックが存在する可能性があることです。いくつかの変数の値に応じてファイルを含めることができます。インクルードされたファイルには、他の「サブインクルード」などが含まれる場合があります。私がこのようにすれば、身体からすべての論理を頭にもコピーしなければならないでしょう。それはあまり効率的ではありません。また、body内のインクルードを削除することにした場合、head内のincludeを削除することをほぼ間違いなく忘れてしまいます。 – Karolis

関連する問題