-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Enable access to local variables in extensions #860
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
For including of templates, the local variables are available because the return value of |
One solution would be to extend ContextReference to allow locals to be included (whilst still defaulting to the existing behaviour): diff --git a/jinja2/compiler.py b/jinja2/compiler.py
index 5135a77..6cfe750 100644
--- a/jinja2/compiler.py
+++ b/jinja2/compiler.py
@@ -1670,7 +1670,10 @@ class CodeGenerator(NodeVisitor):
self.write(node.name)
def visit_ContextReference(self, node, frame):
- self.write('context')
+ if node.include_locals:
+ self.write(self.derive_context(frame))
+ else:
+ self.write('context')
def visit_Continue(self, node, frame):
self.writeline('continue', node)
diff --git a/jinja2/nodes.py b/jinja2/nodes.py
index 5ab2b31..61f2dd6 100644
--- a/jinja2/nodes.py
+++ b/jinja2/nodes.py
@@ -943,6 +943,7 @@ class ContextReference(Expr):
Assign(Name('foo', ctx='store'),
Getattr(ContextReference(), 'name'))
"""
+ attributes = ('include_locals',)
class Continue(Stmt): |
An alternative would be to use a separate node type to provide the locals, but playing with that locally I just ended up doing the context.derive(locals) call myself; I don't know if there are many cases where extension authors would want the locals without the rest of the context, which is (I think) the only use case that approach would enable that the above diff doesn't. |
This allows extensions to access locals in the scope from which they were called, fixing pallets#860.
This allows extensions to access locals in the scope from which they were called, fixing pallets#860.
As far as I can tell, there is no way for extensions to access local variables from their call site, they can only access the template context (which, for example, excludes loop-local variables).
Template Code
Using the extension at https://review.openstack.org/#/c/568021/5/jenkins_jobs/jinja2_extension.py, and
the
context
passed by a ContextReference in_render_template
looks like:Note that
y
is in the context, but none ofx
,z
ora
are.Your Environment
The text was updated successfully, but these errors were encountered: