Serializing data to JSON

Templating to serialize data as JSON to be used in javascript on the page.

Example of outputting a variable that contains a list of items.

Example list ["First Item", "Second Item"]

{% set myitems = ["First Item", "Second Item"] %}
var someVariable = {{ myitems|tojson|safe }};

Would output:

var someVariable = ["First Item", "Second Item"];

From External Context

If you are using an External Context in your template, you can serialize any filtered output to JSON.

{% set results = external_context_name.filter({"city": "Seattle"}) %}
var someItems = {{ results|tojson|safe }};

Would output:

var someItems = [{"name" "Item 1", "city": "Seattle"},...];