@ -127,6 +127,20 @@ Example:
on any filename passed via ` ` ! include - raw - escape : ` ` the tag will be
automatically converted to ` ` ! include - raw : ` ` and no escaping will be
performed .
The tag ` ` ! include - jinja2 : ` ` will treat the given string or list of strings as
filenames to be opened as Jinja2 templates , which should be rendered to a
string and included in the calling YAML construct . ( This is analogous to the
templating that will happen with ` ` ! include - raw ` ` . )
Examples :
. . literalinclude : : / . . / . . / tests / yamlparser / fixtures / jinja01 . yaml
contents of jinja01 . yaml . inc :
. . literalinclude : : / . . / . . / tests / yamlparser / fixtures / jinja01 . yaml . inc
"""
import functools
@ -135,6 +149,7 @@ import logging
import os
import re
import jinja2
import yaml
from yaml . constructor import BaseConstructor
from yaml . representer import BaseRepresenter
@ -349,8 +364,8 @@ class YamlInclude(BaseYAMLObject):
elif isinstance ( node , yaml . SequenceNode ) :
contents = [ cls . _from_file ( loader , scalar_node )
for scalar_node in node . value ]
if any ( isinstance ( s , Lazy Loader) for s in contents ) :
return Lazy LoaderCollection( contents )
if any ( isinstance ( s , Custom Loader) for s in contents ) :
return Custom LoaderCollection( contents )
return u ' \n ' . join ( contents )
else :
@ -383,6 +398,17 @@ class YamlIncludeRawEscape(YamlIncludeRaw):
return loader . escape_callback ( data )
class YamlIncludeJinja2 ( YamlIncludeRaw ) :
yaml_tag = u ' !include-jinja2: '
@classmethod
def _from_file ( cls , loader , node ) :
contents = cls . _open_file ( loader , node )
if isinstance ( contents , LazyLoader ) :
return contents
return Jinja2Loader ( contents )
class DeprecatedTag ( BaseYAMLObject ) :
@classmethod
@ -407,8 +433,22 @@ class YamlIncludeRawEscapeDeprecated(DeprecatedTag):
_new = YamlIncludeRawEscape
class LazyLoaderCollection ( object ) :
""" Helper class to format a collection of LazyLoader objects """
class CustomLoader ( object ) :
""" Parent class for non-standard loaders. """
class Jinja2Loader ( CustomLoader ) :
""" A loader for Jinja2-templated files. """
def __init__ ( self , contents ) :
self . _template = jinja2 . Template ( contents )
self . _template . environment . undefined = jinja2 . StrictUndefined
def format ( self , * * kwargs ) :
return self . _template . render ( kwargs )
class CustomLoaderCollection ( object ) :
""" Helper class to format a collection of CustomLoader objects """
def __init__ ( self , sequence ) :
self . _data = sequence
@ -416,7 +456,7 @@ class LazyLoaderCollection(object):
return u ' \n ' . join ( item . format ( * args , * * kwargs ) for item in self . _data )
class LazyLoader ( object ) :
class LazyLoader ( CustomLoader ) :
""" Helper class to provide lazy loading of files included using !include*
tags where the path to the given file contains unresolved placeholders .
"""