当前位置: 首页>>代码示例>>Python>>正文


Python jinja2.Template方法代码示例

本文整理汇总了Python中jinja2.Template方法的典型用法代码示例。如果您正苦于以下问题:Python jinja2.Template方法的具体用法?Python jinja2.Template怎么用?Python jinja2.Template使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在jinja2的用法示例。


在下文中一共展示了jinja2.Template方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: traceback_response

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Template [as 别名]
def traceback_response() -> Response:
    type_, value, tb = sys.exc_info()
    frames = []
    while tb:
        frame = tb.tb_frame
        try:
            code = inspect.getsourcelines(frame)
        except OSError:
            code = None

        frames.append(
            {
                "file": inspect.getfile(frame),
                "line": frame.f_lineno,
                "locals": frame.f_locals,
                "code": code,
            }
        )
        tb = tb.tb_next

    name = type_.__name__
    template = Template(TEMPLATE)
    html = template.render(frames=reversed(frames), name=name, value=value)
    return Response(html, 500) 
开发者ID:pgjones,项目名称:quart,代码行数:26,代码来源:debug.py

示例2: add_model

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Template [as 别名]
def add_model(self, model_type: str, model_uuid: str, meta: dict,
                  template_model: Template, update_default: bool=False):
        """Add a new model to the registry. Call `upload()` to update the remote side."""
        if update_default or model_type not in self.meta:
            self.meta[model_type] = meta["default"]
        model_meta = meta["model"]
        self.models.setdefault(model_type, {})[model_uuid] = model_meta
        model_directory = os.path.join(self.cached_repo, model_type)
        os.makedirs(model_directory, exist_ok=True)
        model = os.path.join(model_directory, model_uuid + ".md")
        if os.path.exists(model):
            os.remove(model)
        links = {}
        for m_type, items in self.models.items():
            for uuid in items:
                if uuid in model_meta["dependencies"]:
                    links[uuid] = os.path.join("/", m_type, "%s.md" % uuid)
        with open(model, "w") as fout:
            fout.write(template_model.render(model_type=model_type, model_uuid=model_uuid,
                                             meta=model_meta, links=links, spdx=LICENSES))
        git.add(self.cached_repo, [model])
        self._log.info("Added %s", model) 
开发者ID:src-d,项目名称:modelforge,代码行数:24,代码来源:index.py

示例3: load_template

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Template [as 别名]
def load_template(self, template: str) -> Template:
        """Load a Jinja2 template from the source directory."""
        env = dict(trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=False)
        jinja2_ext = ".jinja2"
        if not template.endswith(jinja2_ext):
            self._log.error("Template file name must end with %s" % jinja2_ext)
            raise ValueError
        if not template[:-len(jinja2_ext)].endswith(".md"):
            self._log.error("Template file should be a Markdown file")
            raise ValueError
        if not os.path.isabs(template):
            template = os.path.join(os.path.dirname(__file__), template)
        with open(template, encoding="utf-8") as fin:
            template_obj = Template(fin.read(), **env)
        template_obj.filename = template
        self._log.info("Loaded %s", template)
        return template_obj 
开发者ID:src-d,项目名称:modelforge,代码行数:19,代码来源:index.py

示例4: html_explore

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Template [as 别名]
def html_explore(report):
    jdata = [{
        'model_name': 'YOLO_v2',
        'performance': {
            szname: {
                'attributes': [
                    {'n': o['n'], 'recalls': {1: o['recall']}} for o in szattr['attributes']
                ],
            } for szname, szattr in report['performance'].items()
        },
    }]
    with open('explore_cls.template.html') as f:
        template = Template(f.read())
    with codecs.open(settings.PROPOSAL_EXPLORE if proposal else settings.DETECTION_EXPLORE, 'w', 'utf-8') as f:
        f.write(template.render({
            'title': 'Explore detection performance',
            'chartjs': get_chartjs(),
            'performance_all': json.dumps(jdata, sort_keys=True),
            'attributes': settings.ATTRIBUTES,
        })) 
开发者ID:yuantailing,项目名称:ctw-baseline,代码行数:22,代码来源:detection_perf.py

示例5: get_template

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Template [as 别名]
def get_template(filename_or_string, is_string=False):
    '''
    Gets a jinja2 ``Template`` object for the input filename or string, with caching
    based on the filename of the template, or the SHA1 of the input string.
    '''

    # Cache against string sha or just the filename
    cache_key = sha1_hash(filename_or_string) if is_string else filename_or_string

    if cache_key in TEMPLATES:
        return TEMPLATES[cache_key]

    if is_string:
        # Set the input string as our template
        template_string = filename_or_string

    else:
        # Load template data into memory
        with open(filename_or_string, 'r') as file_io:
            template_string = file_io.read()

    TEMPLATES[cache_key] = Template(template_string, keep_trailing_newline=True)
    return TEMPLATES[cache_key] 
开发者ID:Fizzadar,项目名称:pyinfra,代码行数:25,代码来源:util.py

示例6: make_html

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Template [as 别名]
def make_html(rows, header=[], tb_class='pretty'):
    "Produce an HTML table"
    back_color = "#F0FFFF" # light blue
    grid_color = "#DCDCDC"
    padding = "5px"
    style = "border:1px solid %s; padding: %s" % (grid_color, padding)
    templ = Template("""
<table class="{{ tb_class }}" style="background-color: {{ back_color}}; {{ style }}">
    {% for item in header %}
    <th style="{{ style }}">{{ item }}</th>
    {% endfor %}
    {% for row in rows %}
        <tr>
        {% for item in row %}
            <td style="vertical-align:top; {{ style }}">{{ item }}</td>
        {% endfor %}
        </tr>
    {% endfor %}
</table>
    """)
    return templ.render(locals()) 
开发者ID:fralau,项目名称:mkdocs_macros_plugin,代码行数:23,代码来源:context.py

示例7: create

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Template [as 别名]
def create(self):
        """
        This method creates a SVG chart.
        :return: (string) contents of the SVG file
        """

        # variables for drawing
        grid = self.__grid_coordinates()
        objs = {
            "grid": grid,
            "labels": self.__txt_coordinates(grid),
            "reference": self.area_coordinates(self.reference, grid),
            "whisky": self.area_coordinates(self.comparison, grid),
            "center_x": self.center_x,
            "center_y": self.center_y,
        }

        # generate the svg
        basedir = app.config["BASEDIR"]
        template = basedir.child("whiskyton", "templates", "chart.svg")
        with open(template, "r") as file_handler:

            # create SVG
            svg_template = Template(file_handler.read())
            return html_minify(svg_template.render(**objs), parser="xml") 
开发者ID:cuducos,项目名称:whiskyton,代码行数:27,代码来源:charts.py

示例8: load_workflow_template

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Template [as 别名]
def load_workflow_template(workflow_template: str) -> jinja2.Template:
    """
    Loads the Jinja2 Template from a specified path

    Parameters
    ----------
    workflow_template: str
        Path to a workflow template

    Returns
    -------
    jinja2.Template
        Loaded but non-rendered jinja2 template for the workflow
    """
    path_to_workflow_template = os.path.abspath(workflow_template)
    template_dir = os.path.dirname(path_to_workflow_template)

    templateEnv = jinja2.Environment(
        loader=jinja2.FileSystemLoader(template_dir), undefined=jinja2.StrictUndefined
    )
    return templateEnv.get_template(os.path.basename(workflow_template)) 
开发者ID:equinor,项目名称:gordo,代码行数:23,代码来源:workflow_generator.py

示例9: _run_sql_script

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Template [as 别名]
def _run_sql_script(ctx, script_name, template_params=None):
    """
    Run SQL commands from a file over the import database.
    If `template_params` is not None, the file is interpreted as a Jinja
    template.
    """
    script_path = os.path.join(ctx.imposm_config_dir, script_name)

    with open(script_path, 'r') as f:
        sql_commands = f.read()

        if template_params is not None:
            sql_commands = (
                jinja2.Template(sql_commands).render(**template_params)
            )

        return _execute_sql(
            ctx,
            sql_commands,
            db=ctx.pg.import_database,
            additional_options="--set ON_ERROR_STOP='1'"
        ) 
开发者ID:QwantResearch,项目名称:kartotherian_docker,代码行数:24,代码来源:tasks.py

示例10: split_code_at_show

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Template [as 别名]
def split_code_at_show(text):
    """
    Split code at plt.show()

    """

    parts = []
    is_doctest = contains_doctest(text)

    part = []
    for line in text.split("\n"):
        if (not is_doctest and line.strip() == 'plt.show()') or \
               (is_doctest and line.strip() == '>>> plt.show()'):
            part.append(line)
            parts.append("\n".join(part))
            part = []
        else:
            part.append(line)
    if "\n".join(part).strip():
        parts.append("\n".join(part))
    return parts

#------------------------------------------------------------------------------
# Template
#------------------------------------------------------------------------------ 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:27,代码来源:plot_directive.py

示例11: eval_template

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Template [as 别名]
def eval_template(self, data, ctx=None):
        """Evaluate data as a Jinja2 template.

        :param data: The template
        :param ctx: Optional ctx to inject into the template render
        """
        template = Template(data)
        return template.render(ctx) 
开发者ID:airshipit,项目名称:drydock,代码行数:10,代码来源:bootaction.py

示例12: render_template

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Template [as 别名]
def render_template(template_path, output_path, context, mkdir=False):
    """Render template with jinja

    Args:
      template_path: path to the jinja template
      output_path: path where to write the rendered template
      context: Dictionary containing context variable
    """
    if mkdir:
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
    with open(template_path, "r") as f:
        template = Template(f.read())
    out = template.render(**context)
    with open(output_path, "w") as f:
        f.write(out) 
开发者ID:kipoi,项目名称:models,代码行数:17,代码来源:template.py

示例13: render

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Template [as 别名]
def render(self, html_image):
        template = jinja2.Template(TEMPLATE)
        return template.render(
            html_image=html_image,
            size=self.font_size,
            background=self.background,
            title=self.title,
            font_family=self.font_family,
            width=self.font_size * len(html_image[0]) * 2
        ) 
开发者ID:xlzd,项目名称:img2html,代码行数:12,代码来源:converter.py

示例14: render_template

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Template [as 别名]
def render_template(template_name_or_list: Union[str, List[str]], **context: Any) -> str:
    """Render the template with the context given.

    Arguments:
        template_name_or_list: Template name to render of a list of
            possible template names.
        context: The variables to pass to the template.
    """
    await current_app.update_template_context(context)
    template = current_app.jinja_env.get_or_select_template(template_name_or_list)
    return await _render(template, context) 
开发者ID:pgjones,项目名称:quart,代码行数:13,代码来源:templating.py

示例15: _render

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Template [as 别名]
def _render(template: Template, context: dict) -> str:
    app = current_app._get_current_object()
    await before_render_template.send(app, template=template, context=context)
    rendered_template = await template.render_async(context)
    await template_rendered.send(app, template=template, context=context)
    return rendered_template 
开发者ID:pgjones,项目名称:quart,代码行数:8,代码来源:templating.py


注:本文中的jinja2.Template方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。