1

I try to pass a variable from to a macro:

{% set syName = {
   x: { name: "Schön"},
   y: { name: "Leicht bewölkt"},
   z: { name: "Stark Bewölkt"},
    } 
%}

{% macro prognose(symbol, syName) %}
   <img src="test/{{ symbol }}.png">
   {% for alt in syName %}
      {{ alt.name }}
   {% endfor %}
{% endmacro %}

{{ _self.prognose(  '1' , syName ) }}

So far so good. But this passes all the content from the variable into the macro. I want to trigger x, y, z individually.

So I tried to write it like this: {{ _self.prognose( '1' , syName.x ) }}

This gives the error:

Impossible to access an attribute ("name") on a string variable ("Schön")

How do I have to write this?

5

The first example makes sense because you are passing a multidimensional array (syName), looping through that array, assigns each array within to alt allowing you to then access the values through dot notation ({{ alt.name }}), because alt is an array.

In your second example you are passing through just one array, so when you loop through it, the value in name is assigned to alt as a string. (the value in the array) so you can echo it out just by doing {{ alt }}

So your code could look like:

{% macro prognose(symbol, syName) %}
   <img src="test/{{ symbol }}.png">
   {% for name in syName %}
      {{ name }}
   {% endfor %}
{% endmacro %}

{{ _self.prognose(  '1' , syName.x ) }}

This will output Schön

To make things even easier for yourself, if you are passing just one array i.e syName.x You don't even need the loop as you can just access the value through dot notation:

{% set syName = {
   x: { name: "Schön"},
   y: { name: "Leicht bewölkt"},
   z: { name: "Stark Bewölkt"},
}%}

{% macro prognose(symbol, syName) %}
    <img src="test/{{ symbol }}.png">
    {{ syName.name }} 
{% endmacro %}

{{ _self.prognose('1', syName.x) }}

This will output Schön

| improve this answer | |
  • Thank you. The one with the for loop works now. But you simplified code doesn't. It throws: Impossible to access an attribute ("name") on a NULL variable ("") – KSPR Jun 16 '15 at 9:23
  • That would happen if the value of the array being passed to the macro is null, are you passing calling the macro like {{ _self.prognose( '1' , syName.x ) }} and syName.x is not null? – Alec Ritson Jun 16 '15 at 9:28
  • Yep exactly. But the value of x is not not null, its Schön. – KSPR Jun 16 '15 at 11:45
  • That's bizarre, I've just updated that part of my answer to show the full code i'm using, which is working....can you confirm this is the same as yours? – Alec Ritson Jun 16 '15 at 11:53
  • I copied your code 1:1 and it works. There must be a typo or something in my extended code. I just can't see it right now. But your code is correct. – KSPR Jun 16 '15 at 12:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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