2

We just installed the CMS and like it very much. On the other hand while following the basic tutorial we seem to get the error "Variable "entry" does not exist." on the most simple piece of code. Can someone please see and help us? We tried to just make a simple blog entry following the tutorial on the craft CMS website.

...

<div class="my-8">
  {% for block in entry.postContent.all() %}
    <div class="my-4">
          {% if block.type == 'text' %}
        {{ block.text }}
      {% elseif block.type == 'image' %}
        {% for image in block.image.all() %}
          <img src="{{ image.url }}" alt="{{ image.title }}" />
        {% endfor %}
      {% endif %}
    </div>
  {% endfor %}
</div>

...

Gives error https://speedwindsurfing.nl/blog/dit-is-een-blog-post

The code is in templates/_includes/post-block.twig as mentioned in the howto. https://craftcms.com/docs/getting-started-tutorial/configure/section.html#create-a-category-group

Hope you can help us out

1 Answer 1

1

The problem is that you're using the only keyword when including the post-blocks.twig partial template, in your blog/_entry.html template:

{% include "_includes/post-blocks.twig" with { blocks: entry.postContent.all() } only %}

The only keyword instructs Twig to not make the global context (i.e. all the variables in the upper scope) available to the included template. Hence, the included post-blocks.twig template doesn't have access to the entry variable, which is defined in the upper scope relative to that included template.

To fix the issue, either make the global context (including the entry variable) available to the included template by removing the only keyword:

{% include "_includes/post-blocks.twig" with { blocks: entry.postContent.all() } %}

...or explicitly make the entry variable available to the included template, by including it alongside the blocks variable in context object passed using the with keyword:

{% include "_includes/post-blocks.twig" with { 
    blocks: entry.postContent.all(),
    entry
} only %}

On a general note; I don't know if you have a good reason to use only in this case, but generally it's only needed to avoid variable collisions and similar problems. It can be a matter of preference too; some developers who like to code very defensively will prefer to always include it, alongside any and all variables that they explicitly want the included template to have access to.

1
  • Thanks for the good explanation. We are going to try and see. Thanks again
    – Ron Cooper
    Commented Apr 27, 2023 at 12:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.