Is there a way to pass a list or dict to a template as context?
joe6pack opened this issue · 3 comments
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.
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,
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?
Hey @joe6pack,
Didn't realize you intended to use this on separate pages. The following should work:
- Have each page declare its context like in this example. In your case, this might look like this:
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.
- Cactus will automatically load
"[{'make':'BMW', 'model':'325i'},{'make':'Tesla','model':'X'}]"
into a"cars"
context variable. Unfortunately, it's loaded as astr
, and you probably want it as adict
to be able to iterate on it. - So, use the plugin to do parse the JSON string into a
dict
:
# 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!)