Twig Append Content to Block

2020-08-09 06:09发布

问题:

In twig templating, is it possible to append content to a block?

For example, consider the template files below.

layout.html.twig

<html>
<head>
    <style>
    {% block css %}{% endblock css %}
    </style>
</head>
<body>
{% block content %}{% endblock content %}
</body>
</html>

inner.html.twig

{% block css %} 
a { color: #fff; }
body { background: #f00; }
{% endblock css %}

{% block content %}

Some contents here...
{% include 'myWidget.html.twig' %}

{% endblock content %}

myWidget.html.twig

{% block css %}
div a { color: #777; }
{% endblock css %}
{% block content %}
<div><a>myWidget content here...</a></div>
{% endblock content %}

Notice the block css.. What I am trying to accomplish is that I want to have each content of the block css appended to the layout.html.twig's css block. Thus, the end result should be:

<html>
<head>
    <style>
    a { color: #fff; }
    body { background: #f00; }
    div a { color: #777; }
    </style>
</head>
<body>
Some contents here...
<div><a>myWidget content here...</a></div>
</body>
</html>

回答1:

This should do the trick:

{% block css %}
    {{ parent() }}
    div a { color: #777; }
{% endblock css %}

{% block content %}
    <div><a>myWidget content here...</a></div>
{% endblock content %}


回答2:

Shortcut to append/prepend content to blocks with few content, e.g. a pagetitle

base.html.twig

...
<title>{% block title %}MyApp{% endblock %}</title>
...

template extending base layout

{% extends '::base.html.twig' %}
{% block title 'Page1 - '~parent() %} {# prepend #}
{% block title parent()~' - Page1' %} {# append #}


回答3:

Calling parent() in the child template works, but each child must explicitly accept inheritance from the parent. You can also choose to enforce this inheritance by using a sub-block instead.

inner.html.twig

{% block css %}
    a { color: #fff; }
    body { background: #f00; }
    {% block css_custom %}{% endblock css_custom %}
{% endblock css %}

myWidget.html.twig

{% block css_custom %}
    div a { color: #777; }
{% endblock css_custom %}