Пример #1
0
 def add_step(self, image_path, step, context):
     if step.no_screenshot:
         step_string = resource_string(
             "docme", "assets/noscreenshot_step.html").decode('utf-8')
         t = JinjaTemplate(step_string)
         step_string = t.render(step=step)
         atual_string = BeautifulSoup(self.string, 'html.parser')
         atual_string.find_all(class_="align-middle")[-1].append(
             BeautifulSoup(step_string, 'html.parser'))
         self.string = str(atual_string)
     else:
         if step.vertical:
             if "step_vertical_html" in self.user_options:
                 step_string = open(self.user_options['step_vertical_html'],
                                    "r").read()
             else:
                 step_string = resource_string(
                     "docme", "assets/step_vertical.html").decode('utf-8')
         else:
             if "step_horizontal_html" in self.user_options:
                 step_string = open(
                     self.user_options['step_horizontal_html'], "r").read()
             else:
                 step_string = resource_string(
                     "docme", "assets/step_horizontal.html").decode('utf-8')
         t = JinjaTemplate(step_string)
         self.string += t.render(
             step_screenshot=image_path,
             step=step,
         )
Пример #2
0
    def get(self, request,
            app_label=None, actor=None,
            pk=None, fldname=None, tplname=None, **kw):

        if request.method == 'GET':

            rpt = requested_actor(app_label, actor)
            elem = rpt.get_row_by_pk(None, pk)
            if elem is None:
                raise http.Http404("%s %s does not exist." % (rpt, pk))

            TextFieldTemplate = rt.modules.tinymce.TextFieldTemplate
            if tplname:
                tft = TextFieldTemplate.objects.get(pk=int(tplname))
                if settings.SITE.trusted_templates:
                    #~ return http.HttpResponse(tft.text)
                    template = JinjaTemplate(tft.text)
                    context = dict(request=request,
                                   instance=elem, **rt.modules)
                    return http.HttpResponse(template.render(**context))
                else:
                    return http.HttpResponse(tft.text)

            qs = TextFieldTemplate.objects.all().order_by('name')

            templates = []
            for obj in qs:
                url = dd.plugins.tinymce.build_plain_url(
                    'templates',
                    app_label, actor, pk, fldname, unicode(obj.pk))
                templates.append([
                    unicode(obj.name), url, unicode(obj.description)])
            js = "var tinyMCETemplateList = %s;" % py2js(templates)
            return http.HttpResponse(js, content_type='text/json')
        raise http.Http404("Method %r not supported" % request.method)
Пример #3
0
 def create_template(self):
     path = create_relative_path(
         [*self.template_file_path, self.template_file_name]
     )
     with open(path) as f:
         template = JinjaTemplate(f.read(), undefined=StrictUndefined)
     return template
Пример #4
0
 def render_component(self, child_data=None):
     data = self._load_yaml(child_data=child_data)
     if self.data_type == ITERABLE:
         tmpl = iterableEnviron.get_template(self.component.name)
         return tmpl.render(data)
     else:
         tmpl = JinjaTemplate(self.component.markup)
         return tmpl.render(data)
Пример #5
0
 def __init__(self, name, text=None, applicable_to=""):
     self.name = name
     self.applicable_to = applicable_to
     if text:
         self.template_text = text
     else:
         self.load_from_file(name)
     self.template = JinjaTemplate(self.template_text, trim_blocks=True)
Пример #6
0
 def _parse_content(
     content: Union[Dict[str, Any], str]
 ) -> Union[Dict[str, Any], JinjaTemplate]:
     if not content:
         return {}
     elif isinstance(content, str):
         return JinjaTemplate(content)
     return content
Пример #7
0
    def __init__(self, filename=None, text=None):
        self._filename = filename
        if filename is not None:
            self.text = self.load_text(filename)
        else:
            self.text = text

        if self.text is None:
            raise InvalidTemplateException(self.text)

        self._template = JinjaTemplate(self.text)
Пример #8
0
 def render_dockerfile(self):
     """Render a Dockerfile for building this application."""
     with open(Config.dockerfile_template, 'r') as templatefile:
         template = JinjaTemplate(templatefile.read())
     with open(getpath(self.application_directory, "Dockerfile"),
               'w') as dockerfile:
         dockerfile.write(
             template.render(package=self.package,
                             application=self.application,
                             distro=self.distro,
                             uid=getuid(),
                             gid=getgid()) +
             '\n'  # a hack because apparently rendering the
         )  # template eats the trailing newline
Пример #9
0
 def write_run_script(self):
     """Write a script to run this application to a file."""
     with open(Config.runscript_template) as templatefile:
         template = JinjaTemplate(templatefile.read())
     with open(self.run_script_file, 'w') as run_script_file:
         run_script_file.write(
             template.render(
                 application_directory=self.application_directory,
                 image_name=self.image_name,
                 container_name=self.container_name) +
             '\n'  # a hack because apparently rendering the
         )  # template eats the trailing newline
     chmod(self.run_script_file,
           S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH
           # these bitwise-or'd values basically equate to rwxr-xr-x
           )
Пример #10
0
def render_template(url_name,
                    page_header,
                    fields,
                    data,
                    targets=(),
                    template="gen_table.html",
                    action_urls=[]):
    menu = get_menu(url_name)
    tmpl = JinjaTemplate(open(os.path.join(TEMPLATE_PATH, template)).read())
    return tmpl.render(
        db_performance_menu=menu,
        page_header=page_header,
        fields=fields,
        data=data,
        targets=targets,
        action_urls=action_urls,
    )
Пример #11
0
 def render(self):
     data = self._to_json()
     if self.markup_type == MARKDOWN:
         try:
             return RENDER_MARKDOWN(data)
         except Exception as e:
             return "Markdown error: %s" % e
         return self.data
     if self.markup_type == ITERABLE:
         try:
             tmpl = iterableEnviron.get_template(self.name)
             return tmpl.render(data)
         except Exception as e:
             return "Iterable render error %s" % e
     else:
         # raw jinja no special config or env
         tmpl = JinjaTemplate(self.markup)
         return tmpl.render(data)
Пример #12
0
    def construct(self, event):

        try:
            event["header"][self.key]["template"]
        except KeyError:
            self.logging.error(
                'Header information event["header"]["%s"]["template"] was expected but not found. Event purged.'
                % (self.key))
            raise

        for key in self.header_templates:
            try:
                template = JinjaTemplate(event["header"][self.key][key])
                event["header"][self.key][key] = template.render(
                    **event["data"])
            except Exception as err:
                self.logging.warning(
                    "Failed to convert header key %s.  Reason: %s" % (key))
                raise

        try:
            template = self.templates.get_template(
                event["header"][self.key]["template"])
        except Exception as err:
            self.logging.error(
                "Template %s does not exist as a file in directory %s." %
                (event["header"][self.key]["template"], self.location))
            raise
        else:
            try:
                event["data"] = template.render(**event["data"])
            except Exception as err:
                self.logging.error(
                    'There was an error processing the template. Reason: %s' %
                    (err))
                raise
        return event
Пример #13
0
def render_pretty(invoc_id: int, rows, total_files, file_objs):
    templ = JinjaTemplate("""
<html>
<head>
    <title>Report for {{invoc_id}}</title>
    <style type="text/css">
        body {
            background-color: #EEEEEE;
        }
        td, th {
            border: 2px solid #C7C7C7;
            padding: 10px;
        }
        th {
            text-align: right;
        }
        table {
            margin-bottom: 1em;
            border-collapse: collapse;
        }
    </style>
</head>
<body>
<h1>Public Copy Report for ID#{{invoc_id}}</h1>

<h3>Overall status</h3>
<table>
<tr>
    <th>Count of files</th>
    <th>Sucessful?</th>
</tr>
{% for row in rows %}
<tr>
    <td>{{row.count}}</td>
    <td>{{row.success}}</td>
</tr>
{% endfor %}
<tr>
    <td>{{total_files}}</td>
    <td>Both</td>
</tr>
</table>

<h3>First 5 files that failed</h3>
{% for file in files %}
<table>
<tr>
    <th>file_id</th>
    <td><a href="/viewer/file/{{file.file_id}}" target="_blank">{{file.file_id}}</a></td>
</tr>
<tr>
    <th>collection</th>
    <td>{{file.collection}}</td>
</tr>
<tr>
    <th>site</th>
    <td>{{file.site}}</td>
</tr>
<tr>
    <th>site_id</th>
    <td>{{file.site_id}}</td>
</tr>
<tr>
    <th>filename</th>
    <td>{{file.filename}}</td>
</tr>
<tr>
    <th>third_party_analysis_url</th>
    <td>{{file.third_party_analysis_url}}</td>
</tr>
<tr>
    <th>error_message</th>
    <td>{{file.error_message}}</td>
</tr>
</table>
{% endfor %}

</body>
</html>
    """)

    return HTMLResponse(
        templ.render(invoc_id=invoc_id,
                     rows=rows,
                     total_files=total_files,
                     files=file_objs))
Пример #14
0
 def render_file(self, src, output_file, context):
     #import pdb; pdb.set_trace()
     print(src)
     return self.compiler._write_output_file(
         JinjaTemplate(open(src).read()).render(**context), output_file)
Пример #15
0
 def render_str(self, src, context):
     return JinjaTemplate(src).render(**context)
Пример #16
0
 def _parse_variables(data: Dict[str, Any]) -> Dict[str, JinjaTemplate]:
     return {name: JinjaTemplate(var_tpl) for name, var_tpl
             in data.get("variables", {}).items()}
Пример #17
0
 def render(self, context):
     if DjangoTemplate is not None:
         return DjangoTemplate(self.s).render(context=context)
     else:
         assert JinjaTemplate is not None
         return JinjaTemplate(self.s).render(**context.flatten())
Пример #18
0
 def _parse_variables(data: Dict[str, Any]) -> Dict[str, Any]:
     return {
         name: (JinjaTemplate(var_tpl) if isinstance(var_tpl, str)
                and var_tpl.startswith("{{") else var_tpl)
         for name, var_tpl in data.get("variables", {}).items()
     }
Пример #19
0
 def __interpolate__(self, math):
     t = JinjaTemplate(math.group(0))
     return t.render(**dict(self.items(raw=True)))
Пример #20
0
 def render_as_bytes(self, **kwargs) -> bytes:
     with open(self.path) as fh:
         template = JinjaTemplate(fh.read())
         return template.render(**kwargs).encode()
Пример #21
0
def benchmark_jinja2():
    JinjaTemplate(jinja2_html).render(**context)
Пример #22
0
 def _load_tmpl(self):
     with open(self._tmpl_path) as tmpl:
         return JinjaTemplate(tmpl.read())
Пример #23
0
 def fake_render(self):
     """return Jinja2 Rendered from cfg values"""
     t = JinjaTemplate(self.cfg['t']).render(json.loads(self.cfg['p']))
     return t
Пример #24
0
from java.lang import Object as JavaObject

from jinja2 import Template as JinjaTemplate

import json
import os

# Calculate the Base directory, this is calculated based on the path of the script joined with the current working dir
BASE_DIR = os.path.dirname(os.path.join(os.getcwd(), __path__))
# Make the @template decorator by supplying a template directory. This allows for template inheritance
template = FileSystemLoader([os.path.join(BASE_DIR, "templates")])

ErrorTemplate = JinjaTemplate("""
<!DOCTYPE html>
<html>
<head></head>
<body>{{ errormessage }}</body>
</html>                   
""")

InfoTemplate = JinjaTemplate("""
<!DOCTYPE html>
<html>
<head></head>
<body>
Path: {{ path }}<br />
Parameters:<br/>
<pre><code>
{{ parameters }}
</code></pre>
</body>
Пример #25
0
<tr>{% for col in row.values() %}
    <td>{{ col }}<td/>
    {% end %}
</tr>{% end %}
</table>""")

    def test_tornado():
        """Tornado Template"""
        tornado_tmpl.generate(table=table)


if JinjaTemplate:
    jinja_tmpl = JinjaTemplate("""
<table>
{% for row in table %}
<tr>{% for col in row.values() %}
    <td>{{ col }}<td/>
    {% endfor %}
</tr>{% endfor %}
</table>""")

    def test_jinja2():
        """Jinja2 template"""
        jinja_tmpl.render(table=table)


if LunarTemplate:
    lunar_tmpl = LunarTemplate.Template("""
<table>
{% for row in table %}
<tr>{% for col in row.values() %}
    <td>{{ col }}<td/>