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
)
| 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, |