jinja2

Quoted expression in Jinja2


ChatGPT told me that:

In Jinja2, if an expression is enclosed in quotes (single or double), it is treated as a literal string, and the entire content, including the expression, will be output as-is. Jinja2 does not parse or evaluate expressions within quoted strings.

However I tested the following template:

{% set name = "Jason" -%}
Name: "{{ name }}"

The output is

Name: "Jason"

While according to ChatGPT it should be:

Name: {{ name }}

So is ChatGPT wrong? What is the behavior of double/single quote in jinja2?


Solution

  • So is ChatGPT wrong?

    No.

    When you write:

    Name: "{{ name }}"
    

    The quotes are not part of the Jinja template expression. They are literal text in your document. Jinja only evaluates expressions within {{...}} markers. If you had written this:

    Name: {{ "name" }}
    

    Jinja would interpret "name" as a literal string and the output would be:

    Name: name
    

    And if you had written:

    Name: "{{ "name" }}"
    

    The output would be:

    Name: "name"