Exemple #1
0
    def get_context_data(self, *args, **kwargs):
        ctx = super(TemplateWithContextView, self).get_context_data(*args, **kwargs)

        if self.config and self.config.template_source:
            # Explicit template source(s) takes priority
            if isinstance(self.config.template_source, str):
                # single template source file path
                template_sources = [self.config.template_source]
                if self.template_name and self.template_name != self.config.template_source:
                    self.usage_name = self.template_name
            else:
                # expecting an iterable of template source file paths
                template_sources = self.config.template_source
                self.usage_name = self.template_name
        elif self.template_name:
            # Default template
            template_sources = [self.template_name]

        templates = []
        for source in template_sources:
            # Add dictionary with name and source
            template = get_template(source)
            template_source = highlight(template.template.source, DjangoLexer(), HtmlFormatter())
            templates.append(dict(name=source, source=template_source))
        ctx.update({"templates": templates})

        # Display snippet usage
        if self.usage_name:
            usage = get_template(self.usage_name)
            usage_source = highlight(usage.template.source, DjangoLexer(), HtmlFormatter())
            ctx.update({"usage_source": usage_source})

        if self.context is not None:
            ctx.update(self.context)
        return ctx
Exemple #2
0
def show_jinja(t, width=WIDTH):
    def replace_linebreaks(t):
        """
        st.write does not handle double breaklines very well. When it encounters `\n\n`, it exit the curent <div> block.
        Explicitely replacing all `\n` with their html equivalent to bypass this issue.
        Also stripping the trailing `\n` first.
        """
        return t.strip("\n").replace("\n", "<br/>")

    wrap = textwrap.fill(t, width=width, replace_whitespace=False)
    out = highlight(wrap, DjangoLexer(), HtmlFormatter())
    out = replace_linebreaks(out)
    st.write(out, unsafe_allow_html=True)
Exemple #3
0
def pigmentize(text):
    """searches for <span></span> and replace with HTML pigmented code
    supported languages: python ; html ; css ; emacs ; bash ; hexdump ;
     DjangoLexer"""
    start_code = text.find('<pre>') + 5
    end_code = text.find('</pre')
    code = text[start_code:end_code]
    if code[0:5] == 'python':
        text.replace('<div class="highlight"><pre>' +
                     highlight(code, PythonLexer(), HtmlFormatter()) +
                     '</pre></div>')
    if code[0:4] == 'html':
        text.replace('<div class="highlight"><pre>' +
                     highlight(code, HtmlLexer(), HtmlFormatter()) +
                     '</pre></div>')
    if code[0:3] == 'css':
        text.replace('<div class="highlight"><pre>' +
                     highlight(code, CssLexer(), HtmlFormatter()) +
                     '</pre></div>')
    if code[0:5] == 'emac':
        text.replace('<div class="highlight"><pre>' +
                     highlight(code, EmacsLispLexer(), HtmlFormatter()) +
                     '</pre></div>')
    if code[0:4] == 'bash':
        text.replace('<div class="highlight"><pre>' +
                     highlight(code, BashLexer(), HtmlFormatter()) +
                     '</pre></div>')
    if code[0:7] == 'hexdump':
        text.replace('<div class="highlight"><pre>' +
                     highlight(code, HexdumpLexer(), HtmlFormatter()) +
                     '</pre></div>')
    if code[0:6] == 'django':
        text.replace('<div class="highlight"><pre>' +
                     highlight(code, DjangoLexer(), HtmlFormatter()) +
                     '</pre></div>')
    return (text)
Exemple #4
0
 def analyse_text(text):
     return DjangoLexer.analyse_text(text)
Exemple #5
0
    def render_page(self, root, file):
        input_file = os.path.join(root, file)
        output_file = self.__get_page_filename(input_file)
        partial = yaml.load(open(input_file, "r").read())
        url_root = os.getenv("ROOT_DIRECTORY") or ""
        # if main index page, add version number from VERSION.txt
        if self.__is_main_index(output_file):
            partial['content'] = pystache.render(
                partial['content'], {"version": self.get_version()})
        else:
            partial['pageHeading'] = partial['pageTitle']
            partial['pageTitle'] = (partial['pageTitle'] +
                                    " - Digital Marketplace frontend toolkit")
            if "examples" in partial:
                template_name, template_extension = os.path.splitext(file)
                template_subfolder = root.replace(self.pages_dirname,
                                                  "").strip("/")
                env = Environment(loader=FileSystemLoader(
                    os.path.join(self.repo_root, "toolkit/templates")))
                env.filters.update({
                    'markdown': markdown_filter,
                })
                # used in `toolkit/templates/summary-table.html` for a conditional import statement
                env.globals['PAGES_BUILDER'] = True

                template_file = os.path.join(template_subfolder,
                                             template_name + ".html")
                template = env.get_template(template_file)
                examples = []
                for index, example in enumerate(partial["examples"]):
                    if isinstance(example, dict):
                        example_template = self.parameters_example(
                            template_subfolder, template_name, example)
                        example_markup = template.render(example)
                    else:
                        example_template = example
                        example_markup = env.from_string(
                            example_template).render({})

                    examples.append({
                        "parameters":
                        highlight(example_template, DjangoLexer(),
                                  HtmlFormatter(noclasses=True)),
                        "markup":
                        example_markup,
                        "highlighted_markup":
                        highlight(example_markup, HtmlLexer(),
                                  HtmlFormatter(noclasses=True))
                    })
                partial_data = {
                    "examples": examples,
                    "pageTitle": partial['pageTitle'],
                    "pageDescription": partial.get('pageDescription'),
                    "pageHeading": partial['pageHeading'],
                    "templateFile": template_file,
                    "urlRoot": url_root
                }
                if "grid" in partial:
                    partial_data['grid'] = partial['grid']

                partial['content'] = self.render_include(
                    os.path.join(self.repo_root, "pages_builder", "includes",
                                 "content.html"), partial_data)

        partial['head'] = self.render_include(
            os.path.join(self.repo_root, "pages_builder", "includes",
                         "head.html"), {"url_root": url_root})
        bodyEnd = partial['bodyEnd'] if "bodyEnd" in partial else ""
        partial['bodyEnd'] = self.render_include(
            os.path.join(self.repo_root, "pages_builder", "includes",
                         "bodyEnd.html"), {
                             "url_root": url_root,
                             "bodyEnd": bodyEnd
                         })
        page_render = pystache.render(self.template_view, partial)
        print "\n  " + input_file
        print "▸ " + output_file
        open(output_file, "w+").write(page_render.encode('utf-8'))
Exemple #6
0
    def render_page(self, root, file):
        input_file = os.path.join(root, file)
        output_file = self.__get_page_filename(input_file)
        partial = yaml.safe_load(open(input_file, "r").read())
        url_root = os.getenv("ROOT_DIRECTORY") or ""
        print("\n  " + input_file)
        # for index pages, we want to render variables in the content
        # - add version number from package.json to the main index page
        # - add urlRoot to the nested 'index.html' pages
        if 'index.html' in output_file:
            partial['content'] = pystache.render(
                partial['content'], {"version": self.get_version()})
        else:
            partial['pageHeading'] = partial['pageTitle']
            partial['pageTitle'] = (partial['pageTitle'] +
                                    " - Digital Marketplace frontend toolkit")
            examples_html_only = 'examples_html_only' in partial
            if "examples" in partial:
                template_name, template_extension = os.path.splitext(file)
                template_subfolder = root.replace(self.pages_dirname,
                                                  "").strip("/")
                env = ToolkitEnvironment(loader=FileSystemLoader(
                    os.path.join(self.repo_root, "toolkit/templates")))
                env.add_extension('jinja2.ext.with_')

                template_file = os.path.join(template_subfolder,
                                             template_name + ".html")
                template = None
                # not all of our examples have template files (`_lists.scss`, for example)
                if os.path.isfile(
                        os.path.join(self.repo_root, "toolkit/templates",
                                     template_file)):
                    template = env.get_template(template_file)
                    has_template = True
                else:
                    has_template = False
                examples = []
                for index, example in enumerate(partial["examples"]):
                    grid = partial.get('grid')
                    # If a pattern doesn't have a template in the toolkit, use the jinja from the example
                    if not has_template:
                        template = env.from_string(example)
                    if isinstance(example, dict):
                        # if the example has some html it needs to be displayed,
                        # cache it and remove from the parameters example
                        surrounding_html = example.get('surrounding_html',
                                                       None)
                        if surrounding_html:
                            del example['surrounding_html']

                        example_template = self.parameters_example(
                            template_subfolder, template_name, example)
                        example_markup = template.render(example)
                        if surrounding_html:
                            example_markup = env.from_string(
                                surrounding_html).render(
                                    {'example': example_markup})
                        # set a grid if specified. Example-level grids will overwrite the one for the page
                        grid = example.get('grid', partial.get('grid'))
                    else:
                        example_template = example
                        example_markup = env.from_string(
                            example_template).render({})

                    examples.append({
                        "markup":
                        example_markup,
                        "highlighted_markup":
                        highlight(example_markup, HtmlLexer(),
                                  HtmlFormatter(noclasses=True)),
                        "grid":
                        grid
                    })
                    if template and not examples_html_only:
                        examples[-1].update({
                            "parameters":
                            highlight(example_template, DjangoLexer(),
                                      HtmlFormatter(noclasses=True))
                        })
                partial_data = {
                    "examples": examples,
                    "pageTitle": partial['pageTitle'],
                    "pageDescription": partial.get('pageDescription'),
                    "pageHeading": partial['pageHeading'],
                    "templateFile": template_file,
                    "urlRoot": url_root
                }

                if "grid" in partial:
                    partial_data['grid'] = partial['grid']

                partial['content'] = self.render_include(
                    os.path.join(self.repo_root, "pages_builder", "includes",
                                 "content.html"), partial_data)

        partial['head'] = self.render_include(
            os.path.join(self.repo_root, "pages_builder", "includes",
                         "head.html"), {"url_root": url_root})
        bodyEnd = partial['bodyEnd'] if "bodyEnd" in partial else ""
        partial['bodyEnd'] = self.render_include(
            os.path.join(self.repo_root, "pages_builder", "includes",
                         "bodyEnd.html"), {
                             "url_root": url_root,
                             "bodyEnd": bodyEnd
                         })
        page_render = pystache.render(self.template_view, partial)
        print("▸ " + output_file)
        open(output_file, "wb+").write(page_render.encode('utf-8'))
Exemple #7
0
def show_jinja(t, width=WIDTH):
    wrap = textwrap.fill(t, width=width, replace_whitespace=False)
    out = highlight(wrap, DjangoLexer(), HtmlFormatter())
    st.write(out, unsafe_allow_html=True)