Example #1
0
 def __init__(self, template_path):
     fullpaths = (os.path.join(path, fname)
                  for path, _, fnames in os.walk(template_path)
                  for fname in fnames)
     mapper = dict((fullpath.replace(template_path,''),
                    open(fullpath, 'r').read())
                   for fullpath in fullpaths)
     DictLoader.__init__(self, mapper)
Example #2
0
def Jinja2Render(chart, values, release, data):
    # template = {"parent.yaml":parent, "children.yaml":children}
    env = Environment(loader=DictLoader(data))
    env.filters['quote'] = quote
    env.filters['trimSuffix'] = trimSuffix
    env.filters['trimPrefix'] = trimPrefix
    env.filters['trunc'] = trunc
    env.filters['b64enc'] = b64enc
    env.filters['printf'] = printf
    env.filters['randAlphaNum'] = randAlphaNum
    env.filters['toYaml'] = toYaml
    env.filters['toJson'] = toJson
    env.filters['indent'] = indent
    env.filters['rangein'] = rangein
    env.filters['int64'] = int64
    env.filters['index'] = index
    env.filters['typeOf'] = typeOf
    env.filters['length'] = length
    env.filters['sub'] = sub

    template = env.get_template('_helpers.tpl')
    try:
        txt = template.render(Values=values,
                              Release=release,
                              Chart=chart,
                              Capabilities=CAPABILITIES18)
        tpl = SeparatorTemplate()
        return tpl.toString(txt)

    except Exception, e:
        traceback.print_exc()
        return str(e)
Example #3
0
 def test_import_from_with_context(self):
     env = Environment(loader=DictLoader(
         {"a": "{% macro x() %}{{ foobar }}{% endmacro %}"}))
     t = env.from_string(
         "{% set foobar = 42 %}{% from 'a' import x with context %}{{ x() }}"
     )
     assert t.render() == "42"
Example #4
0
 def getConfigHtml(self):
     filepath = os.path.join(self.get_plugin_isntall_path()['path'], 'config.ji2')
     with open(filepath, "r") as f:
         tpl = f.read()
     env = Environment(loader=DictLoader({'this': tpl}), extensions=['jinja2.ext.i18n'])
     elementTemplate = env.get_template('this')
     return elementTemplate.render(plugin_instance=self.instance, plugin_identifier=self.identifier)
 def addDictonary(self, theme):
     files = theme.get('files', {'templates': {}})
     if files.get('templates'):
         compiled = {}
         for file, content in files.get('templates').items():
             compiled[mongodecode(file)] = content
         self.loaders.append(DictLoader(compiled))
Example #6
0
 def process(self, chain, document:Document, **keyargs):
     '''
     @see: HandlerProcessor.process
     
     Process the jinja templates.
     '''
     assert isinstance(document, Document), 'Invalid document %s' % document
     
     templates = {}
     for path, stream in self.listPaths().items():
         if self._rPatternTemplate.match(path):
             try: templates[path] = stream.read().decode('utf8')
             finally:
                 if isinstance(stream, IClosable): stream.close()
         elif self._rPatternCopy.match(path):
             try: folder = path[:path.index('/')]
             except ValueError: folder = self.pathDocumentation
             else: folder = os.path.join(self.pathDocumentation, folder.replace('/', os.sep))
             
             if not os.path.exists(folder): os.makedirs(folder)
             file = os.path.join(self.pathDocumentation, path.replace('/', os.sep))
             
             try:
                 with open(file, 'wb') as dest: pipe(stream, dest)
             finally:
                 if isinstance(stream, IClosable): stream.close()
     
     document.loader = DictLoader(templates)
 def setUp(self):
     self.hint_generator = Mock(HintGenerator)
     self.tpl_mapping = {}
     self.tpl_helper = TemplateHelper(DictLoader(self.tpl_mapping))
     self.extensionsconf = ExtensionsConf('etc/wazo-confgend/templates/contexts.conf',
                                          self.hint_generator, self.tpl_helper)
     self.output = StringIO()
Example #8
0
 def test_context_include_with_overrides(self, test_env):
     env = Environment(loader=DictLoader(
         dict(
             main=
             "{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}",
             item="{{ item }}",
         )))
     assert env.get_template("main").render() == "123"
Example #9
0
 def test_from_import_with_globals(self, test_env):
     env = Environment(loader=DictLoader(
         {
             "macros": "{% macro testing() %}foo: {{ foo }}{% endmacro %}",
             "test": "{% from 'macros' import testing %}{{ testing() }}",
         }))
     tmpl = env.get_template("test", globals={"foo": "bar"})
     assert tmpl.render() == "foo: bar"
Example #10
0
 def test_import_with_globals_override(self, test_env):
     env = Environment(loader=DictLoader(
         {
             "macros": "{% set foo = '42' %}{% macro test() %}"
             "foo: {{ foo }}{% endmacro %}",
             "test": "{% from 'macros' import test %}{{ test() }}",
         }))
     tmpl = env.get_template("test", globals={"foo": "bar"})
     assert tmpl.render() == "foo: 42"
Example #11
0
def test_env():
    env = Environment(loader=DictLoader(
        dict(
            module="{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}",
            header="[{{ foo }}|{{ 23 }}]",
            o_printer="({{ o }})",
        )))
    env.globals["bar"] = 23
    return env
Example #12
0
def test_import_as_with_context_deterministic(tmp_path):
    src = "\n".join(f'{{% import "bar" as bar{i} with context %}}'
                    for i in range(10))
    env = Environment(loader=DictLoader({"foo": src}))
    env.compile_templates(tmp_path, zip=None)
    name = os.listdir(tmp_path)[0]
    content = (tmp_path / name).read_text("utf8")
    expect = [f"'bar{i}': " for i in range(10)]
    found = re.findall(r"'bar\d': ", content)[:10]
    assert found == expect
Example #13
0
    def test_jinja2_config(self):
        app_config = self.basic_valid_app_config.copy()
        dict_loader = DictLoader({})
        app_config.update({"jinja2": {"loader": dict_loader,
                                      "use_webassets": True}})

        webassets_env = Environment("/tmp", "/")
        webassets_env.register("js", "dummy.js", "dummy2.js", output="dummy.js")
        config = BlueberryPyConfiguration(app_config=app_config,
                                          webassets_env=webassets_env)
        self.assertEqual(config.jinja2_config, {"loader": dict_loader})
Example #14
0
    def test_use_jinja2(self):
        app_config = self.basic_valid_app_config.copy()
        app_config.update({"jinja2": {}})
        self.assertRaisesRegexp(BlueberryPyNotConfiguredError,
                                "Jinja2 configuration not found.",
                                callable_obj=BlueberryPyConfiguration,
                                app_config=app_config)

        app_config.update({"jinja2": {"loader": DictLoader({})}})
        config = BlueberryPyConfiguration(app_config=app_config)
        self.assertTrue(config.use_jinja2)
Example #15
0
def test_filters_deterministic(tmp_path):
    src = "".join(f"{{{{ {i}|filter{i} }}}}" for i in range(10))
    env = Environment(loader=DictLoader({"foo": src}))
    env.filters.update(
        dict.fromkeys((f"filter{i}" for i in range(10)), lambda: None))
    env.compile_templates(tmp_path, zip=None)
    name = os.listdir(tmp_path)[0]
    content = (tmp_path / name).read_text("utf8")
    expect = [f"filters['filter{i}']" for i in range(10)]
    found = re.findall(r"filters\['filter\d']", content)
    assert found == expect
Example #16
0
    def addDictonary(self, theme):
        """
        Add template files as dictionary in the loaders.
        """

        files = theme.get('files', {'templates': {}})
        if files.get('templates'):
            compiled = {}
            for tfile, content in files.get('templates').items():
                compiled[mongodecode(tfile)] = content
            self.loaders.append(DictLoader(compiled))
Example #17
0
    def test_import_with_globals(self, test_env):
        env = Environment(loader=DictLoader(
            {
                "macros": "{% macro test() %}foo: {{ foo }}{% endmacro %}",
                "test": "{% import 'macros' as m %}{{ m.test() }}",
                "test1": "{% import 'macros' as m %}{{ m.test() }}",
            }))
        tmpl = env.get_template("test", globals={"foo": "bar"})
        assert tmpl.render() == "foo: bar"

        tmpl = env.get_template("test1")
        assert tmpl.render() == "foo: "
def load_templated_file(f):
    # read without the import first line
    f.seek(0)
    content_without_import = ''.join(f.readlines()[1:])
    env = Environment(undefined=SilentUndefined,
                      loader=DictLoader(dict()),
                      autoescape=select_autoescape(),
                      variable_start_string="{@",
                      variable_end_string="@}")
    template = env.from_string(content_without_import)
    data = yaml.safe_load(template.render(fim={'watch_files': nop}))
    return data
Example #19
0
  def setUp(self):
    gae_tests.TestCase.setUp(self)
    self.jinja_env = Environment(loader=DictLoader({
      'subject.html': '{{var}}',
      'body.html': '<html>{{var}}</html>',
      'body.txt': '{{var}}',
    }))

    self.flaskapp = flask.Flask(__name__)
    telegram.init_app(self.flaskapp)
    self.flaskapp._app_context = self.flaskapp.app_context()
    self.flaskapp._app_context.push()
Example #20
0
    def buildHtml(self, search=False, curIndex=0):
        if search:
            tpl = self.getSearchTemplate()
        else:
            tpl = self.getTemplate()
        #print "template for %s is #####:\n%s\n" % (self, tpl)

        #TODO: find a way to not initialise a new Environment every time !
        webRoot = common.SYSTEM.c.webRoot
        env = Environment(loader=DictLoader({'this': tpl}),
                          extensions=['jinja2.ext.i18n'])
        env.install_gettext_callables(_, ngettext, newstyle=True)
        env.filters['relativeTime'] = helper.reltime
        env.filters['idSafe'] = helper.idSafe
        env.filters['derefMe'] = helper.dereferMe
        env.filters['derefMeText'] = helper.dereferMeText
        elementTemplate = env.get_template('this')

        widgets_html = {}
        useInSearch = {
            'actionButtons': 'addButton',
            'actionButtonsIcons': 'addButtonIcon',
            'released': 'released'
        }

        for widget in WIDGETS:
            if (widget in useInSearch and search) or not search:
                if "{{%s}}" % widget in tpl:
                    templateName = '%s.html' % widget
                    if search:
                        templateName = '%s.html' % useInSearch[widget]
                    curTemplate = elementWidgetEnvironment.get_template(
                        templateName)
                    widgets_html[widget] = curTemplate.render(
                        this=self,
                        globalStatus=Status.select(),
                        webRoot=webRoot,
                        common=common)

        #Static infos / render stuff
        # status class
        statusCssClass = 'status-any status-%s' % self.status.name.lower()
        # add the field values to the widgets dict. this makes the <field_name> available as {{<field_name>}} in the templates
        widgets_html.update(self.buildFieldDict())

        return elementTemplate.render(children='{{children}}',
                                      this=self,
                                      statusCssClass=statusCssClass,
                                      loopIndex=curIndex,
                                      webRoot=webRoot,
                                      myUrl=self.manager.myUrl(),
                                      common=common,
                                      **widgets_html)
def TestOneInput(data):
    fdp = atheris.FuzzedDataProvider(data)
    template_str = fdp.ConsumeString(sys.maxsize)

    tmp_path = "/tmp/mytemplates"
    temp_file = os.path.join(tmp_path, "template.jinja2")
    if not os.path.isdir(tmp_path):
        os.mkdir(tmp_path)
    if os.path.isfile(temp_file):
        os.remove(temp_file)
    with open(temp_file, "wb") as fd:
        fd.write(data)

    env = Environment(loader=DictLoader({"foo": template_str}))
    try:
        env.compile_templates(tmp_path, zip=None)
    except RecursionError:
        return
    return
Example #22
0
    def test_use_webassets(self):
        app_config = self.basic_valid_app_config.copy()
        app_config.update({"jinja2": {"use_webassets": True,
                                      "loader": DictLoader({})}})
        self.assertRaisesRegexp(BlueberryPyNotConfiguredError,
                                "Webassets configuration not found.",
                                callable_obj=BlueberryPyConfiguration,
                                app_config=app_config)

        webassets_env = Environment("/tmp", "/")
        self.assertRaisesRegexp(BlueberryPyNotConfiguredError,
                                "No bundles found in webassets env.",
                                callable_obj=BlueberryPyConfiguration,
                                app_config=app_config,
                                webassets_env=webassets_env)

        webassets_env = Environment("/tmp", "/")
        webassets_env.register("js", "dummy.js", "dummy2.js", output="dummy.js")
        config = BlueberryPyConfiguration(app_config=app_config,
                                          webassets_env=webassets_env)
        self.assertTrue(config.use_webassets)
Example #23
0
from jinja2 import Environment
from jinja2.loaders import DictLoader

env = Environment(
    loader=DictLoader(
        {
            "a": "[A[{% block body %}{% endblock %}]]",
            "b": "{% extends 'a' %}{% block body %}[B]{% endblock %}",
            "c": "{% extends 'b' %}{% block body %}###{{ super() }}###{% endblock %}",
        }
    )
)
print(env.get_template("c").render())
Example #24
0
def main():
    global output_path
    global G_DATAS
    global G_TEMPLATES
    global ccb_path

    # 支持中文
    reload(sys)
    sys.setdefaultencoding('utf-8')

    # 读取参数
    if len(sys.argv) < 4:
        print "Invalide args! <ccb_path, output_path, template_path>"
        return

    ccb_path = sys.argv[1]
    output_path = sys.argv[2]
    template_path = sys.argv[3]
    print "---------------------------------------------------------------"
    print "ccb_path      : ", ccb_path
    print "output_path   : ", output_path
    print "template_path : ", template_path
    print "---------------------------------------------------------------"

    # 加载所有模板
    G_TEMPLATES = os.listdir(template_path)

    templates = dict((name, open(template_path + "/" + name, 'rb').read())
                     for name in G_TEMPLATES)
    env.loader = DictLoader(templates)

    # 生成目标目录
    if not os.path.isdir(output_path):
        print 'making dir ' + output_path
        os.mkdir(output_path)
    else:
        print 'output dir exist :' + output_path

    # 第一次加载所有ccb文件
    result = []
    listdir_recursive(ccb_path, result, ccb_path)
    print result
    for name in result:
        path_name = os.path.join(ccb_path, name)
        if os.path.isdir(path_name):
            pass
        elif os.path.isfile(path_name) and name.endswith(".ccb"):
            loadCCBData(G_DATAS, name, path_name)

    # 输出下
    output(G_DATAS)

    # 监控ccb文件变化
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
    event_handler = MyEventHandler()
    observer = Observer()
    observer.schedule(event_handler, ccb_path, recursive=True)
    observer.start()

    print "\n"
    try:
        while True:
            time.sleep(1)
            sys.stdout.write(".")
            sys.stdout.flush()

    except KeyboardInterrupt:
        print "\n"
        observer.stop()
    observer.join()
Example #25
0
from __future__ import print_function
from jinja2 import Environment
from jinja2.loaders import DictLoader

env = Environment(loader=DictLoader(
    {
        'child.html': u'''\
{% extends master_layout or 'master.html' %}
{% include helpers = 'helpers.html' %}
{% macro get_the_answer() %}42{% endmacro %}
{% title = 'Hello World' %}
{% block body %}
    {{ get_the_answer() }}
    {{ helpers.conspirate() }}
{% endblock %}
''',
        'master.html': u'''\
<!doctype html>
<title>{{ title }}</title>
{% block body %}{% endblock %}
''',
        'helpers.html': u'''\
{% macro conspirate() %}23{% endmacro %}
'''
    }))

tmpl = env.get_template("child.html")
print(tmpl.render())
Example #26
0
from __future__ import print_function
from jinja2 import Environment
from jinja2.loaders import DictLoader

env = Environment(loader=DictLoader({
    'a':
    '''[A[{% block body %}{% endblock %}]]''',
    'b':
    '''{% extends 'a' %}{% block body %}[B]{% endblock %}''',
    'c':
    '''{% extends 'b' %}{% block body %}###{{ super() }}###{% endblock %}'''
}))

print(env.get_template('c').render())
Example #27
0
    def buildHtml(self, search=False, curIndex=0):
        if search:
            tpl = self.getSearchTemplate()
        else:
            tpl = self.getTemplate()

        webRoot = common.SYSTEM.c.webRoot
        env = Environment(loader=DictLoader({'this': tpl}))
        elementWidgetEnvironment
        elementTemplate = env.get_template('this')
        actionTemplate = None
        infoTemplate = None
        if not search:
            if '{{actionButtons}}' in tpl:
                actionTemplate = elementWidgetEnvironment.get_template(
                    'actions.html')
            elif '{{iconActionButtons}}' in tpl:
                actionTemplate = elementWidgetEnvironment.get_template(
                    'actionsIcons.html')

            if '{{infoButtons}}' in tpl:
                infoTemplate = elementWidgetEnvironment.get_template(
                    'info.html')
            elif '{{iconInfoButtons}}' in tpl:
                infoTemplate = elementWidgetEnvironment.get_template(
                    'infoIcons.html')

            statusTemplate = elementWidgetEnvironment.get_template(
                'status.html')
            statusHtml = statusTemplate.render(this=self,
                                               globalStatus=Status.select(),
                                               webRoot=webRoot)
        else:
            actionTemplate = elementWidgetEnvironment.get_template(
                'actionsAdd.html')
            statusHtml = ''
        # render action buttons
        if actionTemplate is not None:
            actionsHtml = actionTemplate.render(this=self, webRoot=webRoot)
        else:
            actionsHtml = ''
        # render info buttons
        if infoTemplate is not None:
            infoHtml = infoTemplate.render(this=self)
        else:
            infoHtml = ''
        # status class
        statusCssClass = 'status-any status-%s' % self.status.name.lower()
        # downloadbar
        downloadBarHtml = ''
        if '{{downloadProgressBar}}' in tpl:
            downloadBarTemplate = elementWidgetEnvironment.get_template(
                'downloadBar.html')
            downloadBarHtml = downloadBarTemplate.render(this=self,
                                                         webRoot=webRoot)

        return elementTemplate.render(children='{{children}}',
                                      actionButtons=actionsHtml,
                                      iconActionButtons=actionsHtml,
                                      infoButtons=infoHtml,
                                      iconInfoButtons=infoHtml,
                                      statusSelect=statusHtml,
                                      this=self,
                                      statusCssClass=statusCssClass,
                                      loopIndex=curIndex,
                                      downloadProgressBar=downloadBarHtml,
                                      webRoot=webRoot,
                                      **self.buildFieldDict())
Example #28
0
'''

from jinja2 import Environment, PackageLoader
from jinja2.loaders import DictLoader

template_name = "SaunaArrHtml-v1.0.html"
env = Environment(loader=PackageLoader('jinja2_templates', 'templates'))
print dir(env)
#print env.__doc__
template = env.get_template(template_name)
print dir(template)
print template.__doc__
# Now the template can be rendered with a variable
html_out = template.render(report_type = "ARR")
# it is possible to render 
html_out2 = template.render({'report_type':"ARR"})
print html_out.find("ARR")
print html_out2.find("ARR")

# Now we test Dictonary loader
test_template2 = "<h1 style=\"text-align:center;\">IDC Generated Report \
<br/>{{report_type}} Radionuclide Report \
<br/>Noble Gas Version</h1>"

loader2 = DictLoader({'index.html': test_template2})
env2 = Environment(loader = loader2)
template2 = env2.get_template('index.html')

print template2.render({'report_type':u"ARR"})
Example #29
0
from jinja2 import Environment
from jinja2.loaders import DictLoader

env = Environment(loader=DictLoader(
    {
        "child.html": """\
{% extends default_layout or 'default.html' %}
{% include helpers = 'helpers.html' %}
{% macro get_the_answer() %}42{% endmacro %}
{% title = 'Hello World' %}
{% block body %}
    {{ get_the_answer() }}
    {{ helpers.conspirate() }}
{% endblock %}
""",
        "default.html": """\
<!doctype html>
<title>{{ title }}</title>
{% block body %}{% endblock %}
""",
        "helpers.html": """\
{% macro conspirate() %}23{% endmacro %}
""",
    }))
tmpl = env.get_template("child.html")
print(tmpl.render())
Example #30
0
from jinja2 import Environment
from jinja2.loaders import DictLoader

env = Environment(
    loader=DictLoader(
        {
            "child.html": u"""\
{% extends master_layout or 'master.html' %}
{% include helpers = 'helpers.html' %}
{% macro get_the_answer() %}42{% endmacro %}
{% title = 'Hello World' %}
{% block body %}
    {{ get_the_answer() }}
    {{ helpers.conspirate() }}
{% endblock %}
""",
            "master.html": u"""\
<!doctype html>
<title>{{ title }}</title>
{% block body %}{% endblock %}
""",
            "helpers.html": u"""\
{% macro conspirate() %}23{% endmacro %}
""",
        }
    )
)
tmpl = env.get_template("child.html")
print(tmpl.render())