56

この機能を達成するための一般的に「良い」方法はありますか? 「use」タグについて読んだことがありますが、これはこれまでのところ最良のオプションのようですが、外部の html を持ち込めず、ブロックのみを持ち込めないことはまだ好きではありません。

以下の例で「include」タグを使用して、説明しようとしている意図を示します。

#base.html.twig
{% include 'elements/header.html.twig' %}
{% block content %}{% endblock %}
{% include 'elements/footer.html.twig' %}

#header.html.twig
<h1>This is my header</h1>
{% block page_title %} Default Page Title {% endblock %}

#index.html.twig
{% extends 'layouts/base.html.twig' %}
{# I want to be able to do this somehow #}
{% block page_title %} This is my overridden page title {% endblock %}
{% block content %} here is the index page content {% endblock %}
4

5 に答える 5

68

解決策を見つけました。block() 関数を使用して子のブロック コンテンツを取得し、include ステートメントの変数として header.html.twig に渡します。

#base.html.twig
{% include 'elements/header.html.twig' with {page_title: block('page_title')} %}
{% block content %}{% endblock %}
{% include 'elements/footer.html.twig' %}

#header.html.twig
<h1>This is my header</h1>
{% if page_title is empty %}
Default Page Title
{% else %}
{{ page_title }}
{% endif %}

#index.html.twig
{% extends 'layouts/base.html.twig' %}
{% block page_title %} This is my overridden page title {% endblock %}
{% block content %} here is the index page content {% endblock %}
于 2013-08-10T10:24:20.973 に答える
3

それはできます。これは、ビューに変数を渡すことによる問題に対する私の解決策です。

#layout.twig
{% if sidebar is empty %}
    This is the default sidebar text.
{% else %}
    {% block sidebar %}{% endblock %}
{% endif %}
{% block content %}{% endblock %}

#index.twig
{% extends "layout.twig" %}
{% block sidebar %}
    This is the sidebar. It will override the default text.
{% endblock %}

{% block content %}
    This is the content.
{% endblock %}

#index.php (SlimPHP)
$app->render('index.twig', ['sidebar' => true]);

私はSlimPHPを使用しているのでsidebar、ビューに変数を渡すことで呼び出します。これは、ビューに渡されたさまざまな変数を使用してさらに拡張できるため、selectedsidebar1などsidebar2を使用できます。

于 2014-01-22T23:03:29.390 に答える