MCPcopy Create free account
hub / github.com/StackStorm/st2 / render_values

Function render_values

st2common/st2common/util/jinja.py:102–165  ·  view source on GitHub ↗

Render an incoming mapping using context provided in context using Jinja2. Returns a dict containing rendered mapping. :param mapping: Input as a dictionary of key value pairs. :type mapping: ``dict`` :param context: Context to be used for dictionary. :type context: ``dict

(mapping=None, context=None, allow_undefined=False)

Source from the content-addressed store, hash-verified

100
101
102def render_values(mapping=None, context=None, allow_undefined=False):
103 """
104 Render an incoming mapping using context provided in context using Jinja2. Returns a dict
105 containing rendered mapping.
106
107 :param mapping: Input as a dictionary of key value pairs.
108 :type mapping: ``dict``
109
110 :param context: Context to be used for dictionary.
111 :type context: ``dict``
112
113 :rtype: ``dict``
114 """
115
116 if not context or not mapping:
117 return mapping
118
119 # Add in special __context variable that provides an easy way to get access to entire context.
120 # This mean __context is a reserve key word although backwards compat is preserved by making
121 # sure that real context is updated later and therefore will override the __context value.
122 super_context = {}
123 super_context["__context"] = context
124 super_context.update(context)
125
126 env = get_jinja_environment(allow_undefined=allow_undefined)
127 rendered_mapping = {}
128 for k, v in six.iteritems(mapping):
129 # jinja2 works with string so transform list and dict to strings.
130 reverse_json_dumps = False
131 if isinstance(v, dict) or isinstance(v, list):
132 v = json_encode(v)
133 reverse_json_dumps = True
134 else:
135 # Special case for text type to handle unicode
136 if isinstance(v, six.string_types):
137 v = to_unicode(v)
138 else:
139 # Other types (e.g. boolean, etc.)
140 v = str(v)
141
142 try:
143 LOG.info("Rendering string %s. Super context=%s", v, super_context)
144 rendered_v = env.from_string(v).render(super_context)
145 except Exception as e:
146 # Attach key and value which failed the rendering
147 e.key = k
148 e.value = v
149 raise e
150
151 # no change therefore no templatization so pick params from original to retain
152 # original type
153 if rendered_v == v:
154 rendered_mapping[k] = mapping[k]
155 continue
156 if reverse_json_dumps:
157 rendered_v = json_decode(rendered_v)
158 rendered_mapping[k] = rendered_v
159 LOG.info(

Callers 1

Calls 5

json_encodeFunction · 0.90
to_unicodeFunction · 0.90
json_decodeFunction · 0.90
get_jinja_environmentFunction · 0.85
updateMethod · 0.45

Tested by

no test coverage detected