Nunjucks: Appending to a list

Created on 4 Jun 2014  Â·  12Comments  Â·  Source: mozilla/nunjucks

I'm trying to append to a list. Jinja2 docs suggest a similar pattern:

{% do navigation.append('a string') %}

Neither do nor list.append() seems to exist in nunjucks.

Most helpful comment

<<set a = [1,2]>>
<<set a = (a.push(3),a) >>

All 12 comments

You might want to take a look at nunjucks-append to see how this could be implemented with nunjucks.

@sbruchmann Thanks for the pointer; looks a bit out of scope -- but I'll have a closer look.

Did you try push()? They're just JavaScript arrays
On Jun 3, 2014 6:28 PM, "Johan Bergström" [email protected] wrote:

I'm trying to append to a list. Jinja2 docs suggest a similar pattern:

{% do navigation.append('a string') %}

Neither do nor list.append() seems to exist in nunjucks.

—
Reply to this email directly or view it on GitHub
https://github.com/mozilla/nunjucks/issues/240.

@mattbasta Excuse my inexperience, but how would I call push() from a block within a template? Are you perhaps suggesting that I should declare the variable and pass it to the template while rendering?

No. There is no list.append() in Nunjucks because append is a method that comes from Python. Use list.push() instead.

Sorry, should've been closed a while ago.

In what context should I use push? I want to do the same thing. However when I do:

{{ myarray.push(myobj) }}

I'm seeing what looks like an index outputted?

I'm seeing what looks like an index outputted?

That's because you're calling the native array push method which mutates the array and doesn't return the array (unfortunately). If you want the array returned you should write a custom filter. We haven't built this into core because we want to discourage too much of this in templates, as you really should avoid doing this in the template.

Thanks for the quick reply @jlongster. That makes sense, I didn't want to do it in the templates either, I was doing it as a quick fix because I'm waiting for a fellow developer to write the filter.

Ok. For now just put that expression at the top-level of your template and use myarray later, it will be mutated.

<<set a = [1,2]>>
<<set a = (a.push(3),a) >>

@rambo-panda
Your solution works. but how efficient is that?

Was this page helpful?
0 / 5 - 0 ratings