Esempio n. 1
0
 def render_block(self, template, block_name):
     """Return a Jinja2 block as a string."""
     new_context = template.new_context
     if block_name not in template.blocks:
         raise TemplateError("No block with name '{}'".format(block_name))
     lines = template.blocks[block_name](new_context(vars=self.ctx))
     return "".join(lines).strip()
Esempio n. 2
0
def restructuredtext(env, value):
    """
    RestructuredText filter
    """
    try:
        from docutils.core import publish_parts
    except ImportError:
        logger.error(u"Cannot load the docutils library.")
        raise TemplateError(u"Cannot load the docutils library.")

    highlight_source = False
    if hasattr(env.config, 'restructuredtext'):
        highlight_source = getattr(env.config.restructuredtext,
                                   'highlight_source', False)

    if highlight_source:
        import hyde.lib.pygments.rst_directive

    initial_header_level = 4
    overrides = {'initial_header_level': initial_header_level}

    #TODO: load rest config from hyde config
    parts = publish_parts(source=value,
                          writer_name="html",
                          settings_overrides=overrides)
    return parts['html_body']
Esempio n. 3
0
def syntax(env, value, lexer=None, filename=None):
    """
    Processes the contained block using `pygments`
    """
    try:
        import pygments
        from pygments import lexers
        from pygments import formatters
    except ImportError:
        logger.error(u"pygments library is required to"
                     " use syntax highlighting tags.")
        raise TemplateError("Cannot load pygments")

    pyg = (lexers.get_lexer_by_name(lexer)
           if lexer else lexers.guess_lexer(value))
    settings = {}
    if hasattr(env.config, 'syntax'):
        settings = getattr(env.config.syntax, 'options', Expando({})).to_dict()

    formatter = formatters.HtmlFormatter(**settings)
    code = pygments.highlight(value, pyg, formatter)
    code = code.replace('\n\n', '\n&nbsp;\n').replace('\n', '<br />')
    caption = filename if filename else pyg.name
    if hasattr(env.config, 'syntax'):
        if not getattr(env.config.syntax, 'use_figure', True):
            return Markup(code)
    return Markup(
        '<div class="codebox"><figure class="code">%s<figcaption>%s</figcaption></figure></div>\n\n'
        % (code, caption))
Esempio n. 4
0
 def wrapper(text):
     f.is_safe = True
     out = text
     try:
         out = f(text)
     except TypogrifyError, e:
         raise TemplateError(e.message)
 def wrapper(text):
     f.is_safe = True
     out = text
     try:
         out = f(text)
     except TypogrifyError as e:
         raise TemplateError(e.message)
     return jinja2.Markup(out)
Esempio n. 6
0
 def wrapper(eval_ctx, value):
     if hasattr(value, '__html__'):
         value = text_type(soft_unicode(value.__html__()))
     else:
         value = soft_unicode(value)
     try:
         out = func(value)
         return jinja2.Markup(out)
     except TypogrifyError as e:
         raise TemplateError(e.message)
Esempio n. 7
0
def textile(env, value):
    """
    Textile filter with support for extensions.
    """
    try:
        import textile
    except ImportError:
        logger.error(u"Cannot load the textile library.")
        raise TemplateError(u"Cannot load the textile library")
    output = value
    return textile.textile(output)
Esempio n. 8
0
 def parse_template(self, template, ctx=None):
     """
     Parse a template with the Jinja template engine
     """
     ctx = ctx or self.template_context
     if isinstance(template, basestring):
         tmpl = self.load_template(template)
     else:
         from jinja2.exceptions import TemplateError
         raise TemplateError("can't render the given Template")
     return tmpl.render(ctx)
Esempio n. 9
0
def create_template(template_path, context):
    name, raw_content = render_template(template_path, context)

    content_filtered = filter(lambda x: not re.match("^\s*$", x),
                              raw_content.splitlines())
    content_filtered = map(lambda s: s.strip(), content_filtered)

    if not content_filtered:
        raise TemplateError(
            "Content of template is empty, please check your template and parameters"
        )

    return Template(name, content_filtered)
Esempio n. 10
0
def markdown2(env, value):
    """
    Markdown2 filter
    """
    try:
        import markdown2 as md2
    except ImportError:
        logger.error(u"Cannot load the markdown2 library.")
        raise TemplateError(u"Cannot load the markdown2 library")
    output = value
    marked = md2.Markdown(
        extras=["header-ids", "markdown-in-html", "footnotes"])
    # more extras: https://github.com/trentm/python-markdown2/wiki/Extras
    # TODO: load modules from hyde config
    return marked.convert(output)
Esempio n. 11
0
File: jinja.py Progetto: semk/hyde
def markdown(env, value):
    """
    Markdown filter with support for extensions.
    """
    try:
        import markdown as md
    except ImportError:
        logger.error(u"Cannot load the markdown library.")
        raise TemplateError("Cannot load the markdown library")
    output = value
    d = {}
    if hasattr(env.config, 'markdown'):
        d['extensions'] = getattr(env.config.markdown, 'extensions', [])
        d['extension_configs'] = getattr(env.config.markdown,
                                         'extension_configs',
                                         Expando({})).to_dict()
    marked = md.Markdown(**d)

    return marked.convert(output)
Esempio n. 12
0
def restructuredtext(env, value):
    """
    RestructuredText filter
    """
    try:
        from docutils.core import publish_parts
    except ImportError:
        logger.error(u"Cannot load the docutils library.")
        raise TemplateError(u"Cannot load the docutils library.")

    highlight_source = False
    if hasattr(env.config, 'restructuredtext'):
        highlight_source = getattr(env.config.restructuredtext,
                                   'highlight_source', False)

    if highlight_source:
        import hyde.lib.pygments.rst_directive

    parts = publish_parts(source=value, writer_name="html")
    return parts['html_body']
Esempio n. 13
0
def jinja2_output_as_string(impact_report, component_key):
    """Get a given jinja2 component output as string.

    Useful for composing complex document.

    :param impact_report: Impact Report that contains the component key.
    :type impact_report: safe.report.impact_report.ImpactReport

    :param component_key: The key of the component to get the output from.
    :type component_key: str

    :return: output as string.
    :rtype: str

    .. versionadded:: 4.0
    """
    metadata = impact_report.metadata
    for c in metadata.components:
        if c.key == component_key:
            if c.output_format == 'string':
                return c.output or ''
            elif c.output_format == 'file':
                try:
                    filename = os.path.join(impact_report.output_folder,
                                            c.output_path)
                    filename = os.path.abspath(filename)
                    # We need to open the file in UTF-8, the HTML may have
                    # some accents for instance.
                    with codecs.open(filename, 'r', 'utf-8') as f:
                        return f.read()
                except IOError:
                    pass

    raise TemplateError(
        "Can't find component with key '%s' and have an output" %
        component_key)
Esempio n. 14
0
def _strftime(timestamp: Union[int, float], fmt: str = "%Y-%m-%d") -> str:
    if not isinstance(timestamp, (int, float)) or not isinstance(fmt, str):
        raise TemplateError("invalid strftime() invocation")
    return date.fromtimestamp(timestamp).strftime(fmt)