Skip to content
Myr

Merge pull request #1241 from MLH-Fellowship/macros_with_globals

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Fix bug with imported macros and template globals

authored by David Lord · committed by GitHub · parents 5eea6e4, cc792d8 · Browse files · 6 files+70 added−7 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+70 added−7 removed

  • tests:+41 added−0 removed
  • other:+29 added−7 removed

6 files+70 added−7 removed

modified:src/jinja2/asyncsupport.py+2 added-2 removed
114 unmodified lines
115116117def wrap_default_module(original_default_module):118 @internalcode119 def _get_default_module(self):119 def _get_default_module(self, ctx=None):120 if self.environment.is_async:121 raise RuntimeError("Template module attribute is unavailable in async mode")122 return original_default_module(self)122 return original_default_module(self, ctx)123124 return _get_default_module125126
123 unmodified lines
modified:src/jinja2/compiler.py+2 added-2 removed
923 unmodified lines
924 )925 elif self.environment.is_async:926 self.write("_get_default_module_async()")927 else:928 self.write("_get_default_module()")928 self.write("_get_default_module(context)")929 if frame.toplevel and not node.target.startswith("_"):930 self.writeline(f"context.exported_vars.discard({node.target!r})")931932 def visit_FromImport(self, node, frame):
10 unmodified lines
943 )944 elif self.environment.is_async:945 self.write("_get_default_module_async()")946 else:947 self.write("_get_default_module()")947 self.write("_get_default_module(context)")948949 var_names = []950 discarded_names = []951 for name in node.names:
803 unmodified lines
modified:src/jinja2/environment.py+18 added-1 removed
1118 unmodified lines
1119 "This feature is not available for this version of Python"1120 )11211122 @internalcode1123 def _get_default_module(self):1123 def _get_default_module(self, ctx=None):1124 """If a context is passed in, this means that the template was1125 imported. Imported templates have access to the current template's1126 globals by default, but they can only be accessed via the context1127 during runtime.11281129 If there are new globals, we need to create a new1130 module because the cached module is already rendered and will not have1131 access to globals from the current context. This new module is not1132 cached as :attr:`_module` because the template can be imported elsewhere,1133 and it should have access to only the current template's globals.1134 """1135 if ctx is not None:1136 globals = {1137 key: ctx.parent[key] for key in ctx.globals_keys - self.globals.keys()1138 }1139 if globals:1140 return self.make_module(globals)1141 if self._module is not None:1142 return self._module1143 self._module = rv = self.make_module()1144 return rv
187 unmodified lines
modified:src/jinja2/runtime.py+5 added-2 removed
95 unmodified lines
96 parent = dict(parent)97 for key, value in locals.items():98 if value is not missing:99 parent[key] = value100 return environment.context_class(environment, parent, template_name, blocks)100 return environment.context_class(101 environment, parent, template_name, blocks, globals=globals102 )103104105class TemplateReference:106 """The `self` in templates."""
73 unmodified lines
180 # remove it.181 _legacy_resolve_mode = False182 _fast_resolve_mode = False183182 def __init__(self, environment, parent, name, blocks):184 def __init__(self, environment, parent, name, blocks, globals=None):185 self.parent = parent186 self.vars = {}187 self.environment = environment188 self.eval_ctx = EvalContext(self.environment, name)189 self.exported_vars = set()190 self.name = name191 self.globals_keys = set() if globals is None else set(globals)192193 # create the initial mapping of blocks. Whenever template inheritance194 # takes place the runtime will update this mapping with the new blocks195 # from the template.
724 unmodified lines
modified:tests/test_imports.py+41 added
96 unmodified lines
9798 with pytest.raises(UndefinedError, match="does not export the requested name"):99 t.render()100101 def test_import_with_globals(self, test_env):102 env = Environment(103 loader=DictLoader(104 {105 "macros": "{% macro test() %}foo: {{ foo }}{% endmacro %}",106 "test": "{% import 'macros' as m %}{{ m.test() }}",107 "test1": "{% import 'macros' as m %}{{ m.test() }}",108 }109 )110 )111 tmpl = env.get_template("test", globals={"foo": "bar"})112 assert tmpl.render() == "foo: bar"113114 tmpl = env.get_template("test1")115 assert tmpl.render() == "foo: "116117 def test_import_with_globals_override(self, test_env):118 env = Environment(119 loader=DictLoader(120 {121 "macros": "{% set foo = '42' %}{% macro test() %}"122 "foo: {{ foo }}{% endmacro %}",123 "test": "{% from 'macros' import test %}{{ test() }}",124 }125 )126 )127 tmpl = env.get_template("test", globals={"foo": "bar"})128 assert tmpl.render() == "foo: 42"129130 def test_from_import_with_globals(self, test_env):131 env = Environment(132 loader=DictLoader(133 {134 "macros": "{% macro testing() %}foo: {{ foo }}{% endmacro %}",135 "test": "{% from 'macros' import testing %}{{ testing() }}",136 }137 )138 )139 tmpl = env.get_template("test", globals={"foo": "bar"})140 assert tmpl.render() == "foo: bar"141142143class TestIncludes:144 def test_context_include(self, test_env):145 t = test_env.from_string('{% include "header" %}')146 assert t.render(foo=42) == "[42|23]"
77 unmodified lines
modified:CHANGES.rst+2 added
9 unmodified lines
10- Bump Babel optional dependency to >=2.1.11- Remove code that was marked deprecated.12- Use :pep:`451` API to load templates with13 :class:`~loaders.PackageLoader`. :issue:`1168`14- Fix a bug that caused imported macros to not have access to the15 current template's globals. :issue:`688`161718Version 2.11.219--------------
770 unmodified lines