Skip to content

Enable access to local variables in extensions #860

Description

@OddBloke

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

{% set y = 'foo' %}
{% for x in [1, 2] %}
    {% set z = 'bar' %}
    {% for a in [1, 2] %}
        {% jjb_include_raw 'jinja_jjb_include_raw001.sh.inc' %}
    {% endfor %}
{% endfor %}

the context passed by a ContextReference in _render_template looks like:

>>> context
<Context {'range': <class 'range'>, 'dict': <class 'dict'>, 'lipsum': <function generate_lorem_ipsum at 0x7fb8d23a0840>, 'cycler': <class 'jinja2.utils.Cycler'>, 'joiner': <class 'jinja2.utils.Joiner'>, 'namespace': <class 'jinja2.utils.Namespace'>, 'name': 'test-include_jjb', 'param': 'value', 'template-name': 'test-job-{param}', '': '', 'builders': [OrderedDict([('shell', <jenkins_jobs.local_yaml.Jinja2Loader object at 0x7fb8d5e09198>)])], 'y': 'foo'} of None>
>>> pprint.pprint(dict(context))
{'': '',
 'builders': [OrderedDict([('shell',
                            <jenkins_jobs.local_yaml.Jinja2Loader object at 0x7fb8d5e09198>)])],
 'cycler': <class 'jinja2.utils.Cycler'>,
 'dict': <class 'dict'>,
 'joiner': <class 'jinja2.utils.Joiner'>,
 'lipsum': <function generate_lorem_ipsum at 0x7fb8d23a0840>,
 'name': 'test-include_jjb',
 'namespace': <class 'jinja2.utils.Namespace'>,
 'param': 'value',
 'range': <class 'range'>,
 'template-name': 'test-job-{param}',
 'y': 'foo'}

Note that y is in the context, but none of x, z or a are.

Your Environment

  • Python version: 3.6
  • Jinja version: trunk

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions