Exemple #1
0
    def test_def_operations(self):
        """test get/list/has def"""

        template = Template("""

            this is the body

            <%def name="a()">
                this is a
            </%def>

            <%def name="b(x, y)">
                this is b, ${x} ${y}
            </%def>

        """)

        assert template.get_def("a")
        assert template.get_def("b")
        assert_raises(AttributeError, template.get_def, ("c"))

        assert template.has_def("a")
        assert template.has_def("b")
        assert not template.has_def("c")

        defs = template.list_defs()
        assert "a" in defs
        assert "b" in defs
        assert "body" in defs
        assert "c" not in defs
Exemple #2
0
    def test_def_operations(self):
        """test get/list/has def"""

        template = Template("""

            this is the body

            <%def name="a()">
                this is a
            </%def>

            <%def name="b(x, y)">
                this is b, ${x} ${y}
            </%def>

        """)

        assert template.get_def("a")
        assert template.get_def("b")
        assert_raises(AttributeError,
                      template.get_def,
                      ("c")
                      )

        assert template.has_def("a")
        assert template.has_def("b")
        assert not template.has_def("c")

        defs = template.list_defs()
        assert "a" in defs
        assert "b" in defs
        assert "body" in defs
        assert "c" not in defs
Exemple #3
0
class TemplateCollector:
    def __init__(self):
        self._file_set = set()
        self._uber_template = None
        pass

    def register_file(self, *path_elements):
        """Add a file used by the Mako templating engine, to render text. 
        These may be command specific, or format specific."""
        filename = _absolute_file(*path_elements)
        self._file_set.add(filename)
        self._uber_template = None

    def get_template(self, def_name=None):
        if self._uber_template is None:
            buf = StringIO()
            for file in self._file_set:
                t = Template(filename=file)
                buf.write(t.source)

            self._uber_template = Template(buf.getvalue(),
                                           module_directory='/tmp/mako')
            buf.close()

        if self._uber_template.has_def(def_name):
            return self._uber_template.get_def(def_name)
        else:
            return self._uber_template
Exemple #4
0
class PhraseBank:
    def __init__(self, template=None):
        self._phrases = {}
        self._src = template.source if template else ""
        self._template = None

    def set_template(self, template):
        if template:
            self._src = template.source
        self._template = None

    def __setitem__(self, key, value):
        list = self._phrases.setdefault(key, [])
        list.append(value)

    def __getitem__(self, key):
        list = self._phrases[key]
        return list[-1]

    def render(self, defName=None, **data):
        if not self._template:
            src = "%s\n%s" % (self._src, self._generate_mako(self._phrases))
            self._template = Template(src, format_exceptions=False)

        if not defName:
            template = self._template
        elif self.has_key(defName):
            template = self._template.get_def(defName)
        else:
            raise ValueError()
        return render_template(template, TEMPLATE=template, **data)

    def has_key(self, key):
        if self._template and self._template.has_def(key):
            return True
        else:
            return self._phrases.has_key(key)

    def _generate_mako(self, phrase_dict):
        outer_funcs = []
        for phrase_name_and_args, phrase_texts in phrase_dict.items():

            # handle the case where no bracket has been added
            if '__name__' is phrase_name_and_args:
                continue
            if "(" in phrase_name_and_args:
                # slice the arglist of the function.
                open = phrase_name_and_args.index('(')
                phrase_name = phrase_name_and_args[:open]
                ending = phrase_name_and_args[open:]
            else:
                # add one by default
                ending = "()"
                phrase_name = phrase_name_and_args

            # generate an inner def for each value of the phrase we've got.
            inner_func_names = []
            inner_funcs = []
            index = 0
            for phrase in phrase_texts:
                inner_func_name = "_%s_%s" % (index, phrase_name)
                inner_funcs.append("<%%def name='%s%s'>%s</%%def>" %
                                   (inner_func_name, ending, phrase))
                inner_func_names.append(inner_func_name)
                index = index + 1

            outer_dict = {
                'phrase_name': phrase_name,
                'arg_list': ending,
                'inner_funcs': "".join(inner_funcs),
                'inner_func_names': ", ".join(inner_func_names),
            }
            # then generate a custom python routine which will select a random def and call it.
            single_func = """
<%%def name='%(phrase_name)s%(arg_list)s'>%(inner_funcs)s<%%
    fns = [%(inner_func_names)s]
    import random
    random.sample(fns, 1)[0]%(arg_list)s
%%></%%def>""" % outer_dict

            outer_funcs.append(single_func)

        return "\n".join(outer_funcs)