symfonytwigcraftcms

Use a template to set a variable


I'm using craftcms and the template language they use is Twig.

The _layout/base.html:

<!DOCTYPE html>
<html>
<head>
    {% include '_layout/_seo_default.html %}
</head>

_layout/_seo_default.html:

{% if seo is not defined %}
    {% set seo = {title: "Default values for things", description:"Default Description"} %}
{% endif %}
<title>{{ seo.title }}</title>
<meta name="description" content="{{ seo.description }}">

I have a blog/_entry template which shows an entry from the CMS based on the url. The blog/_entry.html:

{% extends '_layout/base.html' %}
{% block main %}
    {# i want this include to set a variable used in _seo_default.html #}
    {% include '_seo/_from_article_type_entry.html' with {entry: entry} %}
    <article>
        html irrelevant to question
    </article>
{% endblock %}

The _seo/_from_article_type_entry.html

{% set seo = { title: entry.title, description: entry.short_description } %}

The idea was that i would be able to map the fields to the correct keys in one template / at one place. So i don't have to reuse it for the news/blog/story templates the client wants. But the 'seo' variable set in _seo/_from_article_type_entry.html does not get set (either not at all, or not in time that the _layout/_seo_default.html picks it up, and default values are always used. If i replace the {% include '_seo/_from_article_type_entry.html' with {entry: entry} %} line in blog/_entry.html with the contents of _seo/_from_article_type_entry.html it does work, so it just doesn't seem to get set in the include. But I can't figure out what i'm missing. Or maybe i'm trying to do something that Twig is not supposed to do. In either case, any help would be very welcome :)


Solution

  • Included templates have their own variable scope, templates outside the included one can't access these variables as seen here


    main.twig

    {% set foo = 'foo' %}
    
    {{ foo }}
    
    {% include 'foo.twig' %}
    
    {{ foo }}
    

    foo.twig

    {% set foo = 'bar' %}
    
    {{ foo }}