Skip to the content.

The main difference between string.Template from Python's string module and jinja2.Template from the Jinja2 templating engine lies in their syntax and features.

Step 1: Creating the Template

string.Template:

from string import Template

temp = Template("Today is $today and tomorrow is $tomorrow.")

jinja2.Template:


from jinja2 import Template

temp = Template("Today is {{today}} and tomorrow is {{tomorrow}}.")

Step 2: Rendering the Template

string.Template:

out = temp.substitute(today="Monday")
print(out)

If you want to avoid an error when a variable is missing, you can use safe_substitute():

out = temp.safe_substitute(today="Monday")
print(out)

jinja2.Template:

out = temp.render(today="Monday")
print(out)

Summary of Differences:

  1. Syntax:

    • string.Template: $variable
    • jinja2.Template: {{variable}}
  2. Rendering:

    • string.Template: Uses substitute() or safe_substitute().
    • jinja2.Template: Uses render().
  3. Error Handling:

    • string.Template:
      • substitute(): Throws a KeyError if any placeholder is missing.
      • safe_substitute(): Leaves missing variables unchanged, without raising an error.
    • jinja2.Template: Leaves missing variables empty (blank) without throwing an error.