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
Provenance
- Commit
9b718ed- Tree
350a873- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
5eea6e4- Parent 2
cc792d8
6 files changed+70 added−7 removed
modified:src/jinja2/asyncsupport.py+2 added-2 removed
114 unmodified lines115 116 117 def 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)123 124 return _get_default_module125 126 123 unmodified linesmodified:src/jinja2/compiler.py+2 added-2 removed
923 unmodified lines924 )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})")931 932 def visit_FromImport(self, node, frame):10 unmodified lines943 )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)")948 949 var_names = []950 discarded_names = []951 for name in node.names:803 unmodified linesmodified:src/jinja2/environment.py+18 added-1 removed
1118 unmodified lines1119 "This feature is not available for this version of Python"1120 )1121 1122 @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.1128+1129+ 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 rv187 unmodified linesmodified:src/jinja2/runtime.py+5 added-2 removed
95 unmodified lines96 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+ )103 104 105 class TemplateReference:106 """The `self` in templates."""73 unmodified lines180 # remove it.181 _legacy_resolve_mode = False182 _fast_resolve_mode = False183 182- 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)192 193 # 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 linesmodified:tests/test_imports.py+41 added
96 unmodified lines97 98 with pytest.raises(UndefinedError, match="does not export the requested name"):99 t.render()100 101+ 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"113 114+ tmpl = env.get_template("test1")115+ assert tmpl.render() == "foo: "116+117+ 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"129+130+ 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"141+142+143 class 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 linesmodified:CHANGES.rst+2 added
9 unmodified lines10 - 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`16 17 18 Version 2.11.219 --------------770 unmodified lines