pallets / jinja

A very fast and expressive template engine.

Home Page:https://jinja.palletsprojects.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`NeverUndefined` added into `jinja2` library code

chatgpt-api-cn opened this issue · comments

This feature shall let the user to eliminate any kind of undefined variables (the strictest check, compared to StrictUndefined) in jinja2 templates.

We can implement it like:

class NeverUndefined(jinja2.StrictUndefined):
    def __init__(self, *args, **kwargs):
        # ARGS: ("parameter 'myvar2' was not provided",)
        # KWARGS: {'name': 'myvar2'}
        if len(args) == 1:
            info = args[0]
        elif "name" in kwargs.keys():
            info = f"Undefined variable '{kwargs['name']}"
        else:
            infoList = ["Not allowing any undefined variable."]
            infoList.append(f"ARGS: {args}")
            infoList.append(f"KWARGS: {kwargs}")
            info = "\n".join(infoList)

        raise Exception(info)

And use it like:

env = jinja2.Environment(..., undefined=NeverUndefined)

Context provided below:

{% macro mymacro(myparam) %}
content
{% endmacro %}

{# shall emit error below, since not all arguments are passed. #}
{{mymacro()}}

I'm not clear how this is usefully different than strict undefined. The code provided does not look correct, almost like it was generated by chatgpt. If you do need this, you can write it directly in your project, no need for it to be in Jinja.