MCPcopy
hub / github.com/pallets/jinja / compile_expression

Method compile_expression

src/jinja2/environment.py:773–816  ·  view source on GitHub ↗

A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression. If called it returns the result of the expression. This is useful if applications want to use the same rules as Jinja in template "configuration

(
        self, source: str, undefined_to_none: bool = True
    )

Source from the content-addressed store, hash-verified

771 self.handle_exception(source=source_hint)
772
773 def compile_expression(
774 self, source: str, undefined_to_none: bool = True
775 ) -> "TemplateExpression":
776 """A handy helper method that returns a callable that accepts keyword
777 arguments that appear as variables in the expression. If called it
778 returns the result of the expression.
779
780 This is useful if applications want to use the same rules as Jinja
781 in template "configuration files" or similar situations.
782
783 Example usage:
784
785 >>> env = Environment()
786 >>> expr = env.compile_expression('foo == 42')
787 >>> expr(foo=23)
788 False
789 >>> expr(foo=42)
790 True
791
792 Per default the return value is converted to `None` if the
793 expression returns an undefined value. This can be changed
794 by setting `undefined_to_none` to `False`.
795
796 >>> env.compile_expression('var')() is None
797 True
798 >>> env.compile_expression('var', undefined_to_none=False)()
799 Undefined
800
801 .. versionadded:: 2.1
802 """
803 parser = Parser(self, source, state="variable")
804 try:
805 expr = parser.parse_expression()
806 if not parser.stream.eos:
807 raise TemplateSyntaxError(
808 "chunk after expression", parser.stream.current.lineno, None, None
809 )
810 expr.set_environment(self)
811 except TemplateSyntaxError:
812 self.handle_exception(source=source)
813
814 body = [nodes.Assign(nodes.Name("result", "store"), expr, lineno=1)]
815 template = self.from_string(nodes.Template(body, lineno=1))
816 return TemplateExpression(template, undefined_to_none)
817
818 def compile_templates(
819 self,

Callers 1

test_expressionsMethod · 0.80

Calls 7

parse_expressionMethod · 0.95
handle_exceptionMethod · 0.95
from_stringMethod · 0.95
ParserClass · 0.85
TemplateSyntaxErrorClass · 0.85
TemplateExpressionClass · 0.85
set_environmentMethod · 0.80

Tested by 1

test_expressionsMethod · 0.64