Macro for entry loop causing 'null' variable template error

Avery: 5 days ago

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>
{% 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 %}

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?

Ryleigh: 5 days ago

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) }}
{{ blogroll.blogroll(category) }}

will work