eudicots / Cactus

Static site generator for designers. Uses Python and Django templates.
BSD 3-Clause "New" or "Revised" License
3.46k stars 314 forks source link

Is there a way to pass a list or dict to a template as context? #226

Closed joe6pack closed 8 years ago

joe6pack commented 8 years ago

Hello - I'm wondering if there's an existing way to pass a list or dict to a template as context. For example, say I have a list of cars that I want to display in a template. Is there a way I can pass something like the following as context to the template?

cars: [{'make':'BMW', 'model':'325i'},{'make':'Tesla','model':'X'}]

I would then reference them in the template as is typical in Django:

{% for car in cars %}
  {{ car.make }}, {{ car.model }}
{% endfor %}

Thanks for any guidance.

krallin commented 8 years ago

Yes; you can add this directly in plugins/page_context.py:

E.g.:

extra = {
    "CURRENT_PAGE": page  # This is already there
    "cars": [{'make':'BMW', 'model':'325i'},{'make':'Tesla','model':'X'}]  # This is yours
}

Cheers,

joe6pack commented 8 years ago

Thanks, @krallin! This is perhaps a daft question, but one that you probably know well: what is the recommended way to make the things you add in "extra" specific to a post page? Like if I have 10 post pages, each with different sets of cars (using my previous example) - what's the recommended way to add / reference them so that a single posts template can be used for all 10 pages?

krallin commented 8 years ago

Hey @joe6pack,

Didn't realize you intended to use this on separate pages. The following should work:

cars: [{'make':'BMW', 'model':'325i'},{'make':'Tesla','model':'X'}]
{% extends 'car_listing.html' %}

Note: you do need to keep everything in cars on one line.

# At the top
import json

# Way below
extra = {
    "CURRENT_PAGE": page,
    "cars": json.loads(context["cars"])
}

Alternatively, you can also add all the logic in the plugin. Load the list of cars for each page from somewhere, then inspect page.source_path and load a list of cars into the context accordingly.

(This might be more maintainable!)