Skip to content

Jinja

sereto.jinja

get_generic_jinja_env(templates)

Creates a generic Jinja2 environment object.

Parameters:

Name Type Description Default
templates Path | Sequence[Path]

The directory/directories containing template files.

required

Returns:

Type Description
Environment

A Jinja2 environment object.

Source code in sereto/jinja.py
81
82
83
84
85
86
87
88
89
90
91
92
def get_generic_jinja_env(templates: Path | Sequence[Path]) -> Environment:
    """Creates a generic Jinja2 environment object.

    Args:
        templates: The directory/directories containing template files.

    Returns:
        A Jinja2 environment object.
    """
    env: Environment = Environment(autoescape=False, loader=FileSystemLoader(templates))
    env.globals["MANUAL_EDIT_WARNING"] = MANUAL_EDIT_WARNING
    return env

get_tex_jinja_env(templates)

Creates a Jinja2 environment object for rendering TeX templates.

Parameters:

Name Type Description Default
templates Path | Sequence[Path]

The directory/directories containing the TeX template files.

required

Returns:

Type Description
Environment

A Jinja2 environment object that is configured for rendering TeX templates.

Source code in sereto/jinja.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def get_tex_jinja_env(templates: Path | Sequence[Path]) -> Environment:
    """Creates a Jinja2 environment object for rendering TeX templates.

    Args:
        templates: The directory/directories containing the TeX template files.

    Returns:
        A Jinja2 environment object that is configured for rendering TeX templates.
    """
    env: Environment = Environment(
        block_start_string="((*",
        block_end_string="*))",
        variable_start_string="(((",
        variable_end_string=")))",
        comment_start_string="((=",
        comment_end_string="=))",
        autoescape=False,
        loader=FileSystemLoader(templates),
    )

    # TODO: Once Jinja2 allows custom escape functions, we might use autoescape of special TeX characters.
    env.filters["tex"] = tex_escape_filter
    env.filters["yesno"] = yesno_filter
    env.globals["MANUAL_EDIT_WARNING"] = MANUAL_EDIT_WARNING
    env.add_extension("jinja2.ext.debug")

    return env

render_j2(templates, file, vars)

Renders a Jinja2 template.

Parameters:

Name Type Description Default
templates Path | Sequence[Path]

The directory/directories containing the template files.

required
file Path

The path to the template file to be rendered.

required
vars dict[str, Any]

A dictionary of variables to be passed to the Jinja2 template engine.

required

Returns:

Type Description
Iterator[str]

A generator that yields the rendered template as a string.

Source code in sereto/jinja.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def render_j2(templates: Path | Sequence[Path], file: Path, vars: dict[str, Any]) -> Iterator[str]:
    """Renders a Jinja2 template.

    Args:
        templates: The directory/directories containing the template files.
        file: The path to the template file to be rendered.
        vars: A dictionary of variables to be passed to the Jinja2 template engine.

    Returns:
        A generator that yields the rendered template as a string.
    """
    if file.name.endswith(".tex.j2"):
        env: Environment = get_tex_jinja_env(templates=templates)
    elif file.name.endswith(".j2"):
        env = get_generic_jinja_env(templates=templates)
    else:
        raise SeretoValueError("unsupported file type")

    template: Template = env.get_template(
        str(file.relative_to(templates[0] if isinstance(templates, abc_Sequence) else templates))
    )

    return template.generate(vars)

tex_escape_filter(text, default='n/a')

Escape special characters in text for use in TeX.

This function serves as a Jinja2 filter to escape special characters in text for use in TeX. It replaces each special character with its corresponding TeX escape sequence. The default argument can be used to specify a default value to return if text is undefined or empty.

Parameters:

Name Type Description Default
text Any

The text to be escaped.

required
default str

The default value to return if text is undefined or empty. Defaults to 'n/a'.

'n/a'

Returns:

Type Description
str

The escaped text.

Source code in sereto/jinja.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def tex_escape_filter(text: Any, default: str = "n/a") -> str:
    """Escape special characters in text for use in TeX.

    This function serves as a Jinja2 filter to escape special characters in `text` for use in TeX. It replaces each
    special character with its corresponding TeX escape sequence. The `default` argument can be used to specify a
    default value to return if `text` is undefined or empty.

    Args:
        text: The text to be escaped.
        default: The default value to return if `text` is undefined or empty. Defaults to 'n/a'.

    Returns:
        The escaped text.
    """
    if is_undefined(text) or not text:
        text = default

    replacements = {
        "&": r"\&",
        "%": r"\%",
        "$": r"\$",
        "#": r"\#",
        "_": r"\_",
        "{": r"\{",
        "}": r"\}",
        "~": r"\textasciitilde{}",
        "^": r"\^{}",
        "\\": r"\textbackslash{}",
        "<": r"\textless{}",
        ">": r"\textgreater{}",
    }
    return replace_strings(str(text), replacements=replacements)

yesno_filter(value, arg='yes,no,maybe')

Tex filter for converting boolean values to strings.

Given a string mapping values for true, false, and (optionally) None, return one of those strings according to the value: ========== ====================== ================================== Value Argument Outputs ========== ====================== ================================== True "yeah,no,maybe" yeah False "yeah,no,maybe" no None "yeah,no,maybe" maybe None "yeah,no" "no" (converts None to False if no mapping for None is given. ========== ====================== ==================================

Source code in sereto/jinja.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def yesno_filter(value: str | None, arg: str = "yes,no,maybe") -> str:
    """Tex filter for converting boolean values to strings.

    Given a string mapping values for true, false, and (optionally) None,
    return one of those strings according to the value:
    ==========  ======================  ==================================
    Value       Argument                Outputs
    ==========  ======================  ==================================
    ``True``    ``"yeah,no,maybe"``     ``yeah``
    ``False``   ``"yeah,no,maybe"``     ``no``
    ``None``    ``"yeah,no,maybe"``     ``maybe``
    ``None``    ``"yeah,no"``           ``"no"`` (converts None to False
                                        if no mapping for None is given.
    ==========  ======================  ==================================
    """
    bits = arg.split(",")
    if len(bits) < 2 or len(bits) > 3:
        raise SeretoValueError("invalid argument")
    try:
        yes, no, maybe = bits
    except ValueError:
        # Unpack list of wrong size (no "maybe" value provided).
        yes, no, maybe = bits[0], bits[1], bits[1]
    if value is None:
        return maybe
    if value:
        return yes
    return no