Skip to content

Commit 02f48b7

Browse files
author
Xavier Barbosa
committed
added 2 jinja filters: yaml and json
1 parent 18e270d commit 02f48b7

File tree

3 files changed

+80
-2
lines changed

3 files changed

+80
-2
lines changed

doc/ref/renderers/all/salt.renderers.jinja.rst

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,33 @@ the context into the included file is required:
9999
100100
.. _imports: http://jinja.pocoo.org/docs/templates/#import
101101

102+
Variable Serializers
103+
====================
104+
105+
Salt allows to serialize any variable into **json** or **yaml**. For example this
106+
variable::
107+
108+
data:
109+
foo: True
110+
bar: 42
111+
baz:
112+
- 1
113+
- 2
114+
- 3
115+
qux: 2.0
116+
117+
with this template::
118+
119+
yaml -> {{ data|yaml }}
120+
121+
json -> {{ data|json }}
122+
123+
will be rendered has::
124+
125+
yaml -> {bar: 42, baz: [1, 2, 3], foo: true, qux: 2.0}
126+
127+
json -> {"baz": [1, 2, 3], "foo": true, "bar": 42, "qux": 2.0}
128+
102129
Template Inheritance
103130
====================
104131

salt/utils/jinja.py

Lines changed: 51 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,24 @@
55
# Import python libs
66
from os import path
77
import logging
8+
from functools import partial
9+
import json
810

911
# Import third party libs
10-
from jinja2 import BaseLoader
11-
from jinja2.exceptions import TemplateNotFound
12+
from jinja2 import BaseLoader, Markup, TemplateNotFound
13+
from jinja2.ext import Extension
14+
import yaml
1215

1316
# Import salt libs
1417
import salt
1518
import salt.fileclient
1619

1720
log = logging.getLogger(__name__)
1821

22+
__all__ = [
23+
'SaltCacheLoader',
24+
'SerializerExtension'
25+
]
1926

2027
class SaltCacheLoader(BaseLoader):
2128
'''
@@ -88,3 +95,45 @@ def uptodate():
8895
continue
8996
# there is no template file within searchpaths
9097
raise TemplateNotFound(template)
98+
99+
100+
class SerializerExtension(Extension):
101+
"""
102+
Serializes variables.
103+
104+
For example, this dataset:
105+
106+
.. code-block:: python
107+
108+
data = {
109+
"foo": True,
110+
"bar": 42,
111+
"baz": [1, 2, 3],
112+
"qux": 2.0
113+
}
114+
115+
.. code-block:: jinja
116+
117+
yaml = {{ data|yaml }}
118+
json = {{ data|json }}
119+
120+
will be rendered has::
121+
122+
yaml = {bar: 42, baz: [1, 2, 3], foo: true, qux: 2.0}
123+
json = {"baz": [1, 2, 3], "foo": true, "bar": 42, "qux": 2.0}
124+
125+
"""
126+
127+
def __init__(self, environment):
128+
self.environment = environment
129+
environment.filters.update({
130+
'yaml': partial(self.format, formatter='yaml'),
131+
'json': partial(self.format, formatter='json')
132+
})
133+
134+
def format(self, value, formatter, *args, **kwargs):
135+
if formatter == "json":
136+
return Markup(json.dumps(value))
137+
elif formatter == "yaml":
138+
return Markup(yaml.dump(value, default_flow_style=True))
139+
raise ValueError("Serializer {} is not implemented".format(formatter))

salt/utils/templates.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import salt.utils
2222
import salt.exceptions
2323
from salt.utils.jinja import SaltCacheLoader as JinjaSaltCacheLoader
24+
from salt.utils.jinja import SerializerExtension as JinjaSerializerExtension
2425

2526
log = logging.getLogger(__name__)
2627

@@ -107,6 +108,7 @@ def render_jinja_tmpl(tmplstr, context, tmplpath=None):
107108
env_args['extensions'].append('jinja2.ext.do')
108109
if hasattr(jinja2.ext, 'loopcontrols'):
109110
env_args['extensions'].append('jinja2.ext.loopcontrols')
111+
jinja_env.add_extension(JinjaSerializerExtension)
110112

111113
if opts.get('allow_undefined', False):
112114
jinja_env = jinja2.Environment(**env_args)

0 commit comments

Comments
 (0)