當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。