render html report with specified report name and template

    Args:
        report_template (str): specify html report template path
        report_dir (str): specify html report save directory
976198
def render_html_report(summary, report_template=None, report_dir=None):
    
    if not report_template:
        report_template = os.path.join(
            os.path.abspath(os.path.dirname(__file__)),
            "templates",
            "report_template.html"
        )
        logger.log_debug("No html report template specified, use default.")
    else:
        logger.log_info("render with html report template: {}".format(report_template))

    logger.log_info("Start to render Html report ...")

    report_dir = report_dir or os.path.join(os.getcwd(), "reports")
    if not os.path.isdir(report_dir):
        os.makedirs(report_dir)

    start_at_timestamp = int(summary["time"]["start_at"])
    summary["time"]["start_datetime"] = datetime.fromtimestamp(start_at_timestamp).strftime('%Y-%m-%d %H:%M:%S')

    report_path = os.path.join(report_dir, "{}.html".format(start_at_timestamp))

    with io.open(report_template, "r", encoding='utf-8') as fp_r:
        template_content = fp_r.read()
        with io.open(report_path, 'w', encoding='utf-8') as fp_w:
            rendered_content = Template(
                template_content,
                extensions=["jinja2.ext.loopcontrols"]
            ).render(summary)
            fp_w.write(rendered_content)

    logger.log_info("Generated Html report: {}".format(report_path))

    return report_path
1189959
def render_requests_data_to_html(self, data, file_name, context={}):
        """"""
        file_path = os.path.join(self.html_dir, file_name)
        logger.info('Rendering HTML file %s...' % file_path)
        data = format_data(data)
        data.update(context)
        data.update(domain=self.domain)
        with open(file_path, 'w') as fp:
            fp.write(render_template('realtime.html', data))
678993
def gen_file_jinja(self, template_file, data, output, dest_path):
        if not os.path.exists(dest_path):
            os.makedirs(dest_path)
        output = join(dest_path, output)
        logger.debug("Generating: %s" % output)

        
        env = Environment()
        env.loader = FileSystemLoader(self.TEMPLATE_DIR)
        # TODO: undefined=StrictUndefined - this needs fixes in templates
        template = env.get_template(template_file)
        target_text = template.render(data)

        open(output, "w").write(target_text)
        return dirname(output), output
260420
def render_template(env, html_path, template_filename, context):
    
    template = env.get_template(template_filename)
    rendered_html = template.render(**context)  # pylint: disable=no-member
    html_path.write_text(rendered_html, encoding='utf-8')
63071
def _print_html(self):
        
        cur_path = os.path.dirname(os.path.realpath(sys.argv[0]))
        shutil.copytree(cur_path+'webpage/template/', '')
895498
def partial_jinja_template(template_name, name='data', mimetype="text/html"):
    
    def partial_jinja_renderer(result, errors):
        template = get_jinja_template(template_name)
        old = template.environment.undefined
        template.environment.undefined = DebugUndefined
        context = {name: result or Mock(), 'errors': errors}
        rendered = template.render(**context)
        template.environment.undefined = old
        return {'body': rendered, 'mimetype': mimetype}
    return partial_jinja_renderer
1122893
def open_report_template_path(self):
        """"""
        # noinspection PyCallByClass,PyTypeChecker
        directory_name = QFileDialog.getExistingDirectory(
            self,
            self.tr('Templates directory'),
            self.leReportTemplatePath.text(),
            QFileDialog.ShowDirsOnly)
        if directory_name:
            self.leReportTemplatePath.setText(directory_name)
1285218
def render(filename, obj):
    """"""
    template_path = abspath(filename)
    env = jinja_env(template_path)
    template_base = os.path.basename(template_path)
    try:
        parsed_content = env.parse(env
                                   .loader
                                   .get_source(env, template_base))
        template_vars = meta.find_undeclared_variables(parsed_content)
        if template_vars:
            missing_vars(template_vars, parsed_content, obj)

        LOG.debug("rendering %s with %s vars",
                  template_path, len(template_vars))
        return env \
            .get_template(template_base) \
            .render(**obj)
    except jinja2.exceptions.TemplateSyntaxError as exception:
        template_trace = traceback.format_tb(sys.exc_info()[2])
        # Different error context depending on whether it is the
        # pre-render variable scan or not
        if exception.filename:
            template_line = template_trace[len(template_trace) - 1]
            raise aomi_excep.Validation("Bad template %s %s" %
                                        (template_line,
                                         str(exception)))

        template_str = ''
        if isinstance(exception.source, tuple):
            # PyLint seems confused about whether or not this is a tuple
            # pylint: disable=locally-disabled, unsubscriptable-object
            template_str = "Embedded Template\n%s" % exception.source[0]

        raise aomi_excep.Validation("Bad template %s" % str(exception),
                                    source=template_str)

    except jinja2.exceptions.UndefinedError as exception:
        template_traces = [x.strip()
                           for x in traceback.format_tb(sys.exc_info()[2])
                           if 'template code' in x]
        raise aomi_excep.Validation("Missing template variable %s" %
                                    ' '.join(template_traces))
531561
def _save_html_report(self, heads=None, refresh=None):
        
        report = ReportHtml(self)
        heads = heads if heads else {}
        test_report_filename = report.get_current_filename("html")
        report.generate(test_report_filename, title='Test Results', heads=heads, refresh=refresh)

        # Update latest.html in the log root directory
        latest_report_filename = report.get_latest_filename("html")
        report.generate(latest_report_filename, title='Test Results', heads=heads, refresh=refresh)
292097
def render_name(self, template_name, *context, **kwargs):
        
        loader = self._make_loader()
        template = loader.load_name(template_name)
        return self._render_string(template, *context, **kwargs)
783359
def compile(self, name, folder=None, data=None):
        
        template_name = name.replace(os.sep, "")
        if folder is None:
            folder = ""
        full_name = os.path.join(
            folder.strip(os.sep), template_name)
        if data is None:
            data = {}
        try:
            self.templates[template_name] = \
                self.jinja.get_template(full_name).render(data)
        except TemplateNotFound as template_error:
            if current_app.config['DEBUG']:
                raise template_error
1247020
def make_html_page(self, valumap):
        
        logger.info('Making an html report using template %r.', self.html_template)
        fh = open(self.html_template)
        template = fh.read()
        fh.close()

        parts = []
        for sr in self.subreports:
            report_data = [item.html for item in sr.report_data if item.html]
            if report_data:
                parts.append('\n<h2>{1}</h2>\n'.format(sr.title, sr.reptext))
                parts.extend(report_data)
                parts.append('\n<hr/>')
        
        valumap['subreports'] = '\n'.join(parts) # or "\n<<NO SUBREPORT RELATED EVENTS>>\n"
        html_page = Template(template).safe_substitute(valumap)
        return TextPart(fmt='html', text=html_page, ext='html')
1183447
def render_and_write(template_dir, path, context):
    
    env = Environment(loader=FileSystemLoader(template_dir))
    template_file = os.path.basename(path)
    template = env.get_template(template_file)
    log('Rendering from template: %s' % template.name, level=DEBUG)
    rendered_content = template.render(context)
    if not rendered_content:
        log("Render returned None - skipping '%s'" % path,
            level=WARNING)
        return

    write(path, rendered_content.encode('utf-8').strip())
    log('Wrote template %s' % path, level=DEBUG)
899606
def render_link(self, template_pack=TEMPLATE_PACK, **kwargs):
        
        link_template = self.link_template % template_pack
        return render_to_string(link_template, {'link': self})
400483
def render_workflow_html_template(filename, subtemplate, filelists, **kwargs):
    

    dirnam = os.path.dirname(filename)
    makedir(dirnam)

    try:
        filenames = [f.name for filelist in filelists for f in filelist if f is not None]
    except TypeError:
        filenames = []

    # render subtemplate
    subtemplate_dir = pycbc.results.__path__[0] + '/templates/wells'
    env = Environment(loader=FileSystemLoader(subtemplate_dir))
    env.globals.update(get_embedded_config=get_embedded_config)
    env.globals.update(path_exists=os.path.exists)
    env.globals.update(len=len)
    subtemplate = env.get_template(subtemplate)
    context = {'filelists' : filelists,
               'dir' : dirnam}
    context.update(kwargs)
    output = subtemplate.render(context)

    # save as html page
    kwds = {'render-function' : 'render_tmplt',
            'filenames' : ','.join(filenames)}
    save_html_with_metadata(str(output), filename, None, kwds)
314630
def render(request, template_name, context=None, content_type=None, status=None, using=None, logs=None):
    
    if logs:
        obj_logger = ObjectLogger()
        if not isinstance(logs, list):
            logs = [logs, ]
        for log in logs:
            log = obj_logger.log_response(
                log,
                context,
                status=str(status),
                headers='',
                content_type=str(content_type))
            log.save()
    return django_render(
        request,
        template_name,
        context=context,
        content_type=content_type,
        status=status,
        using=using)
861882
def render_template_file(template, context=None):
    
    assert isinstance(context, Mapping)
    template = get_template(template)
    return template.render(context)