Example #1
0
class RenderJinja2:

    postfix = (".html", "htm")

    def __init__(self, *a, **kwargs):
        extensions = kwargs.pop("extensions", [])
        globals = kwargs.pop("globals", {})
        registers = kwargs.pop("registers", {})

        self._lookup = Environment(loader=FileSystemLoader(*a, **kwargs), extensions=extensions)
        self._lookup.globals.update(globals)
        self._lookup.globals.update(registers)

    def render(self, path, **kwargs):
        for fix in self.postfix:
            realpath = path + fix
            try:
                t = self._lookup.get_template(realpath)
                return t.render(**kwargs)
            except:
                pass
        raise TemplateNotFound

    def __getattr__(self, name):
        path = name + ".html"
        t = self._lookup.get_template(path)
        return t.render
Example #2
0
 def render_inline_js(self, package, js):
     template_name = self.package.template_name or "pipeline/inline_js.jinja"
     context = self.package.extra_context
     context.update({"source": js})
     env = Environment(loader=self.loader)
     tpl = env.get_template(template_name)
     return tpl.render(**context)
Example #3
0
def generatehtml(words_and_weighted_frequencies, snippet_generator):
    """output results as html"""
    env = Environment(loader=PackageLoader("goldwaage", "templates"))
    env.filters["drop_boring_entries"] = _annihilate_zero_weights
    env.filters["highlight_word_of_interest"] = _highlight_word_of_interest
    env.filters["check_spelling"] = _check_spelling
    _generate_wordlist_html(words_and_weighted_frequencies, env, snippet_generator)
Example #4
0
 def test_choice_loader(self):
     env = Environment(loader=choice_loader)
     tmpl = env.get_template("justdict.html")
     assert tmpl.render().strip() == "FOO"
     tmpl = env.get_template("test.html")
     assert tmpl.render().strip() == "BAR"
     self.assert_raises(TemplateNotFound, env.get_template, "missing.html")
Example #5
0
def build(outfile, template, content_file):
    content = Content(content_file)
    template_dir, template_file = os.path.split(template)
    output_dir, output_file = os.path.split(outfile)
    env = Environment(
        block_start_string="%{",
        block_end_string="%}",
        variable_start_string="%{{",
        variable_end_string="%}}",
        comment_start_string="%{#",
        comment_end_string="%#}",
        line_comment_prefix="%#",
        line_statement_prefix="%##",
        loader=FileSystemLoader(template_dir),
    )
    template = env.get_template(template_file)
    with codecs.open(outfile, "wb", encoding="utf-8") as f:
        f.write(
            template.render(
                last_updated=format_date(),
                git_hash=content.get_git_hash(),
                schools=content.get_schools(),
                experience=content.get_experience(),
                skills=content.get_skills(),
                languages=content.get_languages(),
            )
        )
    os.system('lualatex -shell-escape --output-directory="' + output_dir + '" ' + outfile)
Example #6
0
    def test_stacked_locals_scoping_bug(self, env):
        env = Environment(line_statement_prefix="#")
        t = env.from_string(
            """\
# for j in [1, 2]:
#   set x = 1
#   for i in [1, 2]:
#     print x
#     if i % 2 == 0:
#       set x = x + 1
#     endif
#   endfor
# endfor
# if a
#   print 'A'
# elif b
#   print 'B'
# elif c == d
#   print 'C'
# else
#   print 'D'
# endif
    """
        )
        assert t.render(a=0, b=False, c=42, d=42.0) == "1111C"
Example #7
0
def execute_programmatically(uid, pipeline, output_dir, notebook=None, script=None, **args):
    try:
        int(uid)
    except ValueError:
        # force it to look like a string in the templated notebook
        uid = "'{}'".format(uid)
    if notebook:
        template_dir = notebooks_path
        suffix = ".ipynb"
    elif script:
        template_dir = scripts_path
        suffix = ".py"
    else:
        raise ValueError("You must supply `notebook` or `script` as a kwarg")

    logger.info("Template directory = %s" % template_dir)
    jinja_env = Environment(loader=FileSystemLoader(template_dir))

    output_path = os.path.join(output_dir, pipeline + suffix)
    logger.info("Writing to %s" % output_path)

    template_name = "%s.tmpl" % pipeline
    logger.info("Loading template = %s" % template_name)

    template = jinja_env.get_template(template_name)
    template_info = {"uid": uid, "version": __version__}
    pipeline = template.render(**template_info)
    with open(output_path, "w") as f:
        f.write(pipeline)
Example #8
0
    def render_templates(self):
        """
			Generate static files from templates
		"""

        # render templates
        import os
        from jinja2 import Environment, FileSystemLoader
        from build.markdown2_extn import Markdown2Extension

        env = Environment(loader=FileSystemLoader("templates"), extensions=[Markdown2Extension])

        # dynamic boot info
        env.globals["boot"] = self.boot()
        env.globals["nav"] = self.nav.html()
        page_info = self.nav.page_info()

        for wt in os.walk("templates"):
            for fname in wt[2]:
                if fname.split(".")[-1] == "html" and not fname.startswith("template"):
                    fpath = os.path.relpath(os.path.join(wt[0], fname), "templates")
                    temp = env.get_template(fpath)

                    env.globals.update(self.nav.page_info_template)
                    env.globals.update(page_info.get(fpath, {}))

                    # out file in parent folder of template
                    f = open(fpath, "w")
                    f.write(temp.render())
                    f.close()
                    print "Rendered %s | %.2fkb" % (fpath, os.path.getsize(fpath) / 1024.0)
Example #9
0
class render_jinja:
    """Rendering interface to Jinja2 Templates
    
    Example:

        render= render_jinja('templates')
        render.hello(name='jinja2')
    """

    def __init__(self, *a, **kwargs):
        extensions = kwargs.pop("extensions", [])
        globals = kwargs.pop("globals", {})

        from jinja2 import Environment, FileSystemLoader

        self._lookup = Environment(loader=FileSystemLoader(*a, **kwargs), extensions=extensions)
        self._lookup.globals.update(globals)

    def __getattr__(self, name):
        # Assuming all templates end with .html
        path = name + ".html"
        try:
            t = self._lookup.get_template(path)
        except Exception, e:
            path = "404.html"
            t = self._lookup.get_template(path)

        return t.render
Example #10
0
class Jinja2Template(BaseTemplate):
    env = None  # hopefully, a Jinja environment is actually thread-safe

    def prepare(self):
        if not self.env:
            from jinja2 import Environment, FunctionLoader

            self.env = Environment(line_statement_prefix="#", loader=FunctionLoader(self.loader))
        if self.template:
            self.tpl = self.env.from_string(self.template)
        else:
            self.tpl = self.env.get_template(self.filename)

    def render(self, **args):
        return self.tpl.render(**args).encode("utf-8")

    def loader(self, name):
        if not name.endswith(".tpl"):
            for path in self.lookup:
                fpath = os.path.join(path, name + ".tpl")
                if os.path.isfile(fpath):
                    name = fpath
                    break
        f = open(name)
        try:
            return f.read()
        finally:
            f.close()
Example #11
0
 def generateClassFiles(self):
     """
     This method assembles all of the attributes of the DAOImpl and writes them to a file based upon the associated template.
     """
     voList = []
     try:
         voList = self.listOfValueObjects()
         deployment_directory = self.__configFileObj.deploymentDirectory(JsonConstants.DEPLOYMODEL)
         self.__deploymentUtil.createDeploymentDirectory(deployment_directory)
         template_directory = os.path.abspath(self.__configFileObj.templateDirectoryName())
         env = Environment(loader=FileSystemLoader(template_directory))
         template = env.get_template(self.__configFileObj.valueObjectTemplateFileName())
         if len(voList) > 0:
             for element in voList:
                 java_file_path = deployment_directory + self.__configFileObj.valueObjectJavaTemplateOutputFileName().replace(
                     "{{ modelName }}", element.modelName
                 )
                 template.stream(
                     {
                         "globalNameSpace": self.__configFileObj.globalClassNameSpace(),
                         "className": element.modelName,
                         "fieldsArray": element.fieldsArray,
                     }
                 ).dump(java_file_path)
     except Exception, error:
         self.__logger.error(
             "*********** ValueObjectClassGenerator.generateClassFiles: Error occurred - {0}".format(str(error))
         )
Example #12
0
def get_var_templates(template):
    env = Environment()
    ast = env.parse(template.content)

    exceptions = ("vidly_tokenize", "edgecast_tokenize", "akamai_tokenize", "popcorn_url", "event")
    undeclared_variables = [x for x in meta.find_undeclared_variables(ast) if x not in exceptions]
    return ["%s=" % v for v in undeclared_variables]
Example #13
0
def render_meta(meta, fn="meta.pandas.html", title="Project Metadata - MSMBuilder", pandas_kwargs=None):
    """Render a metadata dataframe as an html webpage for inspection.

    Parameters
    ----------
    meta : pd.Dataframe
        The DataFrame of metadata
    fn : str
        Output filename (should end in html)
    title : str
        Page title
    pandas_kwargs : dict
        Arguments to be passed to pandas

    """
    if pandas_kwargs is None:
        pandas_kwargs = {}

    kwargs_with_defaults = {"classes": ("table", "table-condensed", "table-hover")}
    kwargs_with_defaults.update(**pandas_kwargs)

    env = Environment(loader=PackageLoader("msmbuilder", "io_templates"))
    templ = env.get_template("twitter-bootstrap.html")
    rendered = templ.render(title=title, content=meta.to_html(**kwargs_with_defaults))

    # Ugh, pandas hardcodes border="1"
    rendered = re.sub(r' border="1"', "", rendered)

    backup(fn)
    with open(fn, "w") as f:
        f.write(rendered)
Example #14
0
def test_spaceless():
    from coffin.template.defaulttags import SpacelessExtension

    env = Environment(extensions=[SpacelessExtension])

    assert (
        env.from_string(
            """{% spaceless %}
<p>
    <a href="foo/">Foo</a>
</p>
{% endspaceless %}"""
        ).render()
        == '<p><a href="foo/">Foo</a></p>'
    )
    assert (
        env.from_string(
            """{% spaceless %}
    <strong>
        Hello
    </strong>
{% endspaceless %}"""
        ).render()
        == "<strong>\n        Hello\n    </strong>"
    )
Example #15
0
    def create_html_file(self, filename):
        """create HTML representation of the LaTeX file"""
        output_lines = []
        title = "kein Titel"
        artist = "kein Artist"
        for line in self.readin_file(filename):
            if self.is_latex(line):
                # extract artist and title information
                if line.startswith("\\subsection"):
                    end = line.find("\\index{")
                    title = line[13:end]
                    start = line.find("\\small ") + len("\\small ")
                    artist = line[start:-3]
                continue
            # add empty line to have space for the chords
            # if self.chord_regex.match(line):
            #    output_lines.append('')
            # include chords HTML command
            line = re.sub(r"\[([^]]+)\]", r"<span>\1</span>", line)
            output_lines.append(line)

        # write song to file using template
        env = Environment(loader=PackageLoader("htmlmaker", "templates"))
        html_filename = self.make_valid_file_name(artist, title)
        with open(os.path.join("pages", html_filename), "w") as fd:
            fd.write(
                env.get_template("song.html").render(title=title, artist=artist, chords="<br/>\n".join(output_lines))
            )
        return artist, title, html_filename
Example #16
0
def expand_yaml_macros(repo, commit_sha, yaml_str):
    if isinstance(yaml_str, six.binary_type):
        yaml_str = yaml_str.decode("utf-8")

    from jinja2 import Environment, StrictUndefined

    jinja_env = Environment(
        loader=GitTemplateLoader(repo, commit_sha),
        # https://github.com/inducer/relate/issues/130
        # loader=YamlBlockEscapingGitTemplateLoader(repo, commit_sha),
        undefined=StrictUndefined,
    )

    # {{{ process explicit [JINJA] tags (deprecated)

    def compute_replacement(match):
        template = jinja_env.from_string(match.group(1))
        return template.render()

    yaml_str, count = JINJA_YAML_RE.subn(compute_replacement, yaml_str)

    if count:
        # The file uses explicit [JINJA] tags. Assume that it doesn't
        # want anything else processed through YAML.
        return yaml_str

    # }}}

    jinja_str = process_yaml_for_expansion(yaml_str)
    template = jinja_env.from_string(jinja_str)
    yaml_str = template.render()

    return yaml_str
Example #17
0
    def run(self, artists_folder):
        # get list of all songs
        all_files = []
        for root, _, files in os.walk(artists_folder):
            all_files.extend([os.path.join(root, f) for f in files if (os.path.splitext(f)[1] == ".tex")])

        # create index
        index = {}
        for f in all_files:
            artist, title, html_filename = self.create_html_file(f)
            entry = index.setdefault(artist, [])
            entry.append((title, html_filename))

        # create index page
        alphabetic_index = {"a": "A-E", "f": "F-K", "l": "L-P", "q": "Q-V", "w": "W-Z"}
        with open("pages/index.html", "w") as fd:
            env = Environment(loader=PackageLoader("htmlmaker", "templates"))
            full_index = []
            last = ""
            for artist, songs in sorted(index.items()):
                if artist[0].lower() in alphabetic_index and last != artist[0].lower():
                    last = artist[0].lower()
                    # set anchor for page index
                    full_index.append('<span class="anchor" id="{}"></span>\n'.format(last))
                for title, path in songs:
                    full_index.append('<a href="{0}">{1} - {2}</a><br/>\n'.format(path, artist, title))
            fd.write(
                env.get_template("index.html").render(
                    alphabetic_index=[(k, v) for k, v in sorted(alphabetic_index.items())], index="".join(full_index)
                )
            )
Example #18
0
def main():
    env = Environment(loader=PackageLoader("webapp", "templates"))
    for templatename in settings.templates:
        template = env.get_template(templatename)
        fp = "{0}/{1}".format(settings.dumpfolder, templatename)
        print "Generating:", fp
        template.stream(data=settings.mydata).dump(fp)
Example #19
0
 def render(self):
     """render posts with template"""
     logger.info(self.render.__doc__)
     env = Environment(loader=FileSystemLoader(self.static_path))
     template = env.get_template("pdf.html")
     self.html = template.render(static_path=self.static_path, posts=self.posts, column=self.column)
     logger.success("rendered")
Example #20
0
def sms():
    """Send an SMS to Twilio and save response to DB. """

    phone_numbers = request.form.getlist("user_phone")

    e = Environment()
    template = ""

    for p in phone_numbers:

        # Render Jinja2 template from message
        u = User.query.filter(User.phone == p).one()
        msg_template = e.from_string(request.form["message"])
        message = msg_template.render(first_name=u.first_name, last_name=u.last_name, phone=p)

        # Send to Twilio
        tw_response = twilio_send(p, message)

        # Convert JSON from Twilio to Python dict
        sms_data = json.loads(tw_response)
        # sms_data = {'to': 1234567899, 'body': 'Fake SMS', 'status': 'fake'}

        # Commit to database
        sms = SentMessage(sms_data["to"], sms_data["body"], sms_data["status"], sms_data["sid"], datetime.now())
        db.session.add(sms)
        template += render_template("new_message.html", message=sms)

    db.session.commit()

    return template
Example #21
0
 def test_filesystem_loader(self):
     env = Environment(loader=filesystem_loader)
     tmpl = env.get_template("test.html")
     assert tmpl.render().strip() == "BAR"
     tmpl = env.get_template("foo/test.html")
     assert tmpl.render().strip() == "FOO"
     self.assert_raises(TemplateNotFound, env.get_template, "missing.html")
Example #22
0
    def _create_environment(self):
        """
        Create the Jinja templating environment.
        """
        from jinja2 import Environment, ChoiceLoader, FileSystemLoader

        here = os.path.dirname(os.path.realpath(__file__))

        paths = self.template_path + [
            os.path.join(here, self.default_template_path),
            os.path.join(here, self.template_skeleton_path),
        ]
        loaders = self.extra_loaders + [FileSystemLoader(paths)]

        environment = Environment(loader=ChoiceLoader(loaders), extensions=JINJA_EXTENSIONS)

        environment.globals["uuid4"] = uuid.uuid4

        # Add default filters to the Jinja2 environment
        for key, value in self.default_filters():
            self._register_filter(environment, key, value)

        # Load user filters.  Overwrite existing filters if need be.
        if self.filters:
            for key, user_filter in self.filters.items():
                self._register_filter(environment, key, user_filter)

        return environment
Example #23
0
 def test_prefix_loader(self):
     env = Environment(loader=prefix_loader)
     tmpl = env.get_template("a/test.html")
     assert tmpl.render().strip() == "BAR"
     tmpl = env.get_template("b/justdict.html")
     assert tmpl.render().strip() == "FOO"
     self.assert_raises(TemplateNotFound, env.get_template, "missing")
Example #24
0
 def ExportClusterSummary(self):
     base_path = "%s/index.html" % self.output_path
     # if os.path.exists(base_path):
     #  return
     LOG(INFO, "exporting cluster summary...")
     cluster_membership = []
     for cluster in self.image_graph.GetClustering(self.output_path):
         cluster_membership.append(cluster)
     cluster_membership.sort(key=lambda n: len(n), reverse=True)
     cluster_info = []
     for cluster_members in cluster_membership:
         cluster_size = len(cluster_members)
         if cluster_size < 5:
             break
         cluster_subgraph = self.image_graph.graph.subgraph(cluster_members)
         centrality = cluster_subgraph.betweenness(directed=False, cutoff=None)
         index, value = max(enumerate(centrality), key=operator.itemgetter(1))
         central_vertex = cluster_subgraph.vs[index]
         # print cluster_size, central_vertex['image_id']
         cluster_info.append(
             (cluster_size, JSPad(central_vertex["image_id"]))
         )  # need str because js can't handle 64 bit int
     env = Environment(loader=PackageLoader("iw.vis.static.imagegraph", "."))
     template = env.get_template("index_template.html")
     CHECK(template)
     params = {"cluster_info": cluster_info}
     html = template.render(params)
     open(base_path, "w").write(html)
     return
Example #25
0
 def generate_wiki(self, data, wiki_template):
     """generates wiki file based on data file and wiki template"""
     env = Environment(loader=FileSystemLoader(TEMPLATES_PATH), undefined=StrictUndefined, trim_blocks=True)
     for b in data.get("builds", []):
         b["issues"] = convert_bugs_to_links(b["issues"])
     template = env.get_template(wiki_template)
     return template.render(**data)
Example #26
0
 def test_lstrip_left_chars(self):
     env = Environment(lstrip_blocks=True, trim_blocks=False)
     tmpl = env.from_string(
         """    abc {% if True %}
     hello{% endif %}"""
     )
     assert tmpl.render() == "    abc \n        hello"
Example #27
0
def post(today, name, format, title, category, authors, tags, summary):

    if not os.path.isfile("pelicanconf.py"):
        raise PostError('"pelicanconf.py" must exist in current directory')

    if not os.path.isdir("content"):
        raise PostError('"content" directory does not exist')

    title = title or name

    jinja_environment = Environment()
    jinja_environment.filters["rst_title"] = rst_title
    jinja_environment.filters["pelican_datetime"] = pelican_datetime

    template = jinja_environment.from_string(templates[format])
    #
    slug = slugify.slugify(title, to_lower=True)

    filename = "%s-%s.%s" % (today.strftime("%Y-%m-%d"), slugify.slugify(name, to_lower=True), format)

    article_path = os.path.join("content", category)

    try:
        os.makedirs(article_path)

    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise

    with open(os.path.join(article_path, filename), "w") as f:
        f.write(
            template.render(
                title=title, date=today, tags=tags, slug=slug, category=category, summary=summary, authors=authors
            )
        )
Example #28
0
 def test_balancing(self):
     env = Environment("{%", "%}", "${", "}")
     tmpl = env.from_string(
         """{% for item in seq
         %}${{'foo': item}|upper}{% endfor %}"""
     )
     assert tmpl.render(seq=list(range(3))) == "{'FOO': 0}{'FOO': 1}{'FOO': 2}"
Example #29
0
def main(source_dir, output_dir):
    # Directories to copy, of the form [(<source_path>, <output_path>), ...]
    to_copy = [("style", "style"), ("images", "images"), ("scripts", "assets")]

    # Directories used to build the page
    template_dir = os.path.join(source_dir, "templates")
    page_dir = os.path.join(source_dir, "pages")

    # Copy assets to output
    for src, dst in to_copy:
        src = os.path.join(source_dir, src)
        dst = os.path.join(output_dir, dst)
        copytree(src, dst)

    # Render pages
    env = Environment(loader=FileSystemLoader(template_dir), trim_blocks=True)
    template = env.get_template("page_template.html")
    for src in gen_find("*.md", page_dir):
        # Get the file's base name
        filename = os.path.basename(src)
        base, _ = os.path.splitext(filename)
        dst = os.path.join(output_dir, base + ".html")

        # Render the page body with customized markdown
        body = render_markdown(open(src, "r").read())
        rendered = template.render(body=body, mathjax_url=mathjax_url, livejs_url=livejs_url)

        # Progress update
        print(src, " ---> ", dst)
        with open(dst, "w") as f:
            f.write(rendered)
Example #30
0
def create_application(**kwargs):
    """ Create a new instance of the application

    :param db_host: The host of the database to use
    :param db_port: The port of the database to use
    :param with_static: A flag indicating if static should be used
    """
    ap_root = os.path.dirname(__file__)
    db_host = kwargs.get("db_host", "localhost")
    db_port = kwargs.get("db_port", 6379)
    config = {"/static": os.path.join(ap_root, "static"), "/templates": os.path.join(ap_root, "templates")}

    if kwargs.get("debug", True):
        logging.getLogger().setLevel(logging.DEBUG)
        logging.basicConfig()

    database = redis.Redis(db_host, db_port)
    loader = FileSystemLoader(config["/templates"])
    template = Environment(loader=loader, autoescape=True)
    template.filters["hostname"] = get_hostname
    instance = Shortly(database, template)

    if kwargs.get("with_static", True):
        instance.wsgi_app = SharedDataMiddleware(instance.wsgi_app, config)
    return instance