简体   繁体   中英

How to Manage Assets in yii2 using twig in child template?

I want to extend my base twig template with some asset bundles and add new assets in child template.

{# main.twig #}
register_asset_bundle('app/assets/AppAsset')

{# child.twig #}
{% extends 'layouts/main.twig' %}
register_asset_bundle('app/assets/NewAsset')

So I got error "A template that extends another one cannot include content outside Twig blocks. Did you forget to put the content inside a {% block %} tag?" So need I to set each asset to blocks? That is uncomfortable when I use asset bundles. Google have no one solutions for this, what should I do in this situation?

It is required for a child template to have its content strictly in the block tags. The engine substitutes the parent blocks for the blocks defined in the child.

Therefore, your main.twig template should include at least one block , eg:

register_asset_bundle('app/assets/AppAsset')
{% block content %}{% endblock %}

So that the child can override it as follows:

{% extends 'layouts/main.twig' %}
{% block content %}
    register_asset_bundle('app/assets/NewAsset')
    {# More content here #}
{% endblock %}

Whatever you put into the "content" block in the parent template will be replaced with the content of that block defined in the child.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM