turik
turik

Reputation: 86

Swig (node.js) Include a File and pass an object

I am facing this problem.

I've got a page with an include of another like this:

index.html

{{ set pets = { pets : petsObject } }}
{{ include pets.html }}

petsObject is an object like this

petsObjects: [
{ name : "cat" },
{ name : "dog" }
]

When I try to render the page I get a blank page with only this:

[object Object]

I have no clue about what is going on :(

Thanks in advance!

Upvotes: 4

Views: 5240

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123433

Seems you'll need to use:

{% include pets.html with pets %}

According to docs for include:

Locally declared context variables are not passed to the included template by default.

It is also recommended for performance to use the only keyword after the included terms, like this:

{% include pets.html with pets only %}

Beyond that, it depends on the contents of pets.html, which you haven't included here. But, make sure that you're attempting to output the name:

{% for pet in pets %}
  {{ pet.name }}
{% endfor %}

Or use a filter like json_encode() to format it:

{% for pet in pets %}
  {{ pet|json_encode }}
{% endfor %}

Trying to output the Objects themselves will simply produce [object Object]:

new Object().toString() === "[object Object]"

Upvotes: 9

Related Questions