1

I am new to the concept of Twig templates and I can’t get it right from the documentation … What I am trying to achieve is to have a reusable Blogroll snippet that outputs entries in different contexts: ALL entries on the homepage and then according to the entry’s category in other areas of the site.

I created a file blogroll.html in templates/macros containing my blogroll code which works fine if used directly in a template (simplified the HTML here):

{% macro blogroll(entry) %}
<a href="{{ entry.url }}">
  <h2>{{ entry.title }}</h2>
</a>
{% endmacro %}

In my index.html for the homepage I try inserting it with this code:

<section class="blogroll">
{% for entry in craft.entries.section('blog').limit(15).find() %}
{% for entry in entries %}
  {% import "macros/blogroll" as blogroll %}
  {{ blogroll.blogroll }}
{% endfor %}
</section>

In my category related templates I filter for the category first and try to insert it this way:

{% set entries = craft.entries.relatedTo(category) %}
{% for entry in entries %}
  {% import "macros/blogroll" as blogroll %}
{{ blogroll.blogroll }}
{% endfor %}

In both cases I get a Impossible to access an attribute ("url") on a null variable. error though.

Any hints where I am not getting the concept right or screw something up while passing the variable?

1 Answer 1

2

Your blogroll can be treated as a PHP function. In order to use functions you have to pass the required parameters. In your case your blogroll expects the parameter entry

{{ blogroll.blogroll(entry) }}
or
{{ blogroll.blogroll(category) }}

will work

1
  • Perfect, thanks! Seems like I was indeed simply missing that parameter.
    – Tobias S.
    Commented Apr 3, 2018 at 12:38

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.