Function json

Source
pub fn json(value: impl Serialize) -> Result<impl Display, Infallible>
Expand description

Serialize to JSON (requires json feature)

The generated string does not contain ampersands &, chevrons < >, or apostrophes '. To use it in a <script> you can combine it with the safe filter:

<script>
var data = {{data|json|safe}};
</script>

To use it in HTML attributes, you can either use it in quotation marks "{{data|json}}" as is, or in apostrophes with the (optional) safe filter '{{data|json|safe}}'. In HTML texts the output of e.g. <pre>{{data|json|safe}}</pre> is safe, too.

/// ```jinja
/// <div><li data-extra='{{data|json|safe}}'>Example</li></div>
/// ```

#[derive(Template)]
#[template(ext = "html", in_doc = true)]
struct Example<'a> {
    data: Vec<&'a str>,
}

assert_eq!(
    Example { data: vec!["foo", "bar"] }.to_string(),
    "<div><li data-extra='[\"foo\",\"bar\"]'>Example</li></div>"
);