4

I have a block that looks like this:

{% if grains['function'] == 'production' %}
{% set conf_src = "prod.yml.ninja" %}
{% elif grains['function'] == 'staging'] %}
{% set conf_src = "staging.yml.ninja" %}
{% elif grains['function'] == 'dev'] %}
{% set conf_src = "dev.yml.ninja" %}
{% endif %}

Is there any way to do something like

{% 
    if grains['function'] == 'production'
        set conf_src = "prod.yml.ninja"
    elif grains['function'] == 'staging'
        set conf_src = "staging.yml.ninja"
    elif grains['function'] == 'dev'
        set conf_src = "dev.yml.ninja"
    endif
%}

So I can just open the block once?

1 Answer 1

1

You can define a look-up dictionary, and only include non-trivial cases:

html = '''
{% set lookup = dict(production='prod') %}
{% set conf_src = lookup.get(grains['function'], grains['function']) 
                + '.yml.ninja' %}
'''

Here, since dev and staging are not modified, you may use dict.get fall-back argument.

1
  • 1
    great example of using dict() inside a jinja2 variable set declaration invents_gusts_grain
    – dreftymac
    Commented Jul 30, 2015 at 1:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.