Jinja Templates

Jinja is a powerful templating engine for Python & Dart, commonly used for rendering HTML templates

Jinja Syntax Documentation for HTML Templates

Home documentation

Overview

Jinja is a powerful templating engine for Python & Dart, commonly used for rendering HTML templates. It provides a flexible syntax for integrating logic into your HTML files. Below are key Jinja features and their usage in HTML templates.

Basic Syntax

Printing Variables

To output the value of a variable in a Jinja template, use the following syntax:

<?= variable ?>

Example:

<p>Hello, <?= username ?>!</p>

This will render:

<p>Hello, Alice!</p>

Comments

To add comments in a Jinja template that will not appear in the rendered HTML, use:

<?# comment ?>

Example:

<?# This is a comment that will not be visible in the rendered HTML ?>
<p>Content here...</p>

Control Structures

If Statements

To include conditional logic in your template, use the if statement:

<? if condition ?>
    <!-- Content to display if condition is true -->
<? endif ?>

Example:

<? if user.is_authenticated ?>
    <p>Welcome back, <?= user.name ?>!</p>
<? else ?>
    <p>Please log in.</p>
<? endif ?>

For Loops

To iterate over a collection, use the for loop:

<? for item in collection ?>
    <p><?= item ?></p>
<? endfor ?>

Example:

<ul>
<? for item in items ?>
    <li><?= item ?></li>
<? endfor ?>
</ul>

Elseif

To handle multiple conditions, use elif in combination with if:

<? if condition1 ?>
    <!-- Content for condition1 -->
<? elif condition2 ?>
    <!-- Content for condition2 -->
<? else ?>
    <!-- Content if none of the conditions are true -->
<? endif ?>

Example:

<? if user.role == 'admin' ?>
    <p>Admin dashboard</p>
<? elif user.role == 'member' ?>
    <p>Member dashboard</p>
<? else ?>
    <p>Public content</p>
<? endif ?>

String Formatting

Jinja supports string formatting using its format method:

<p><?= "Hello, {name}".format(name=username) ?></p>

Example:

<p><?= "Your balance is {:.2f}".format(balance) ?></p>

This will render:

<p>Your balance is 1234.56</p>

Includes

To include other templates within a template, use the include statement:

<? include 'template.html' ?>

Example:

<? include 'header.html' ?>
<h1>Page Title</h1>
<? include 'footer.html' ?>

Extends

To extend a base template and override specific blocks, use the extends and block statements:

Extending a Template

<? extends 'base.html' ?>

Defining Blocks

In the extended template, define blocks to be overridden:

<!-- base.html -->
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}Default Title{% endblock %}</title>
</head>
<body>
    <header>{% block header %}Default Header{% endblock %}</header>
    <main>
        {% block content %}Default Content{% endblock %}
    </main>
    <footer>{% block footer %}Default Footer{% endblock %}</footer>
</body>
</html>

Overriding Blocks

In the extending template, override blocks as needed:

<!-- page.html -->
<? extends 'base.html' ?>

<? block title ?>
    Custom Page Title
<? endblock ?>

<? block header ?>
    Custom Header Content
<? endblock ?>

<? block content ?>
    <p>This is the custom content of the page.</p>
<? endblock ?>

<? block footer ?>
    Custom Footer Content
<? endblock ?>

Adding Variables to Widgets in Controllers

When developing with the WebApp package in Dart, you might need to pass variables from your controllers to the views or widgets for rendering. This process is similar to how you would handle variables in Jinja or other template engines. Here’s a comprehensive guide on how to accomplish this in your Dart controllers.

1. Using rq.addParam for Single Variables

If you need to add a single variable to your request, use the addParam method. This is useful for straightforward cases where only a few variables are involved.

rq.addParam('name', variable);

Parameters:

  • 'name': The key or name of the variable you want to add.
  • variable: The value of the variable.

Example Usage:

Future<String> exampleMethod() async {
  String userName = 'John Doe';
  rq.addParam('userName', userName);
  return renderTemplate('example/template');
}

In this example, the variable userName is added to the request with the key 'userName'. You can then access this variable in your template.

2. Using rq.addParams for Multiple Variables

For adding multiple variables at once, use the addParams method. This approach is ideal when dealing with multiple variables or a collection of parameters.

rq.addParams({
  'exampleTString': TString('example.tstring').write(rq),
  'examplePathString': 'example.path'.tr.write(rq),
  'exampleTranslateParams': 'example.params'.tr.write(rq, {
    'name': 'Alexandre',
    'age': Random().nextInt(100),
  }),
});

Parameters:

  • 'exampleTString': The key for the first variable, with a value generated by TString.
  • 'examplePathString': A translated string.
  • 'exampleTranslateParams': A translated string with dynamic parameters.

Example Usage:

Future<String> exampleMethod() async {
  rq.addParams({
    'welcomeMessage': 'Welcome to the site!',
    'currentYear': DateTime.now().year,
    'userDetails': {
      'name': 'Alice',
      'age': 30,
    },
  });
  return renderTemplate('example/template');
}

In this example, multiple variables are added to the request in one go. The welcomeMessage, currentYear, and userDetails are all available for use in the template.

Rendering Templates

To render a template with the added variables, use the renderTemplate method. This will compile the template and inject the variables into it.

Future<String> renderTemplate(String widget) async {
  rq.addParams({
    'title': 'My Awesome App',
    'year': DateTime.now().year,
    'user': await getUserDetails(),
  });

  return rq.renderView(path: "template/home");
}

Parameters:

  • 'title': A static string for the title.
  • 'year': The current year.
  • 'user': User details fetched from some method.

Summary

Jinja syntax allows you to embed logic and variables into your HTML templates efficiently. By using control structures like if statements and for loops, formatting strings, and including or extending templates, you can create dynamic and reusable HTML content. This documentation provides a foundation for using Jinja in your projects, enhancing your ability to manage and render templates effectively.

And in controllers use rq.addParams or getParams

  • Use rq.addParam for adding single variables.
  • Use rq.addParams for adding multiple variables at once.
  • Render templates using renderTemplate after adding the necessary variables.

This approach helps in efficiently managing and rendering dynamic content in your web application, similar to how you would handle variables in Jinja or other templating systems.