Exemplo n.º 1
0
def get_render_callable(engine_name, displays_on, src, filename=None):
    """ Returns a function that takes a template source and kwargs. """

    # See the discussion here re: `displays_on` -- http://bit.ly/JRqbRw

    directory = None
    if filename:

        if SEP not in filename and (not ALTSEP or ALTSEP not in filename):
            filename = _get_dotted_filename(engine_name, filename)

        directory = os.path.dirname(filename)

    if engine_name == 'mako':
        import mako.template
        args = dict(text=src,
                    imports=["from markupsafe import escape_silent"],
                    default_filters=['escape_silent'])

        if filename:
            args['filename'] = relpath(filename, directory)
            from mako.lookup import TemplateLookup
            args['lookup'] = TemplateLookup(directories=[directory])

        tmpl = mako.template.Template(**args)
        return lambda kwargs: Markup(tmpl.render(**kwargs))

    elif engine_name in ('genshi', 'genshi_abs'):
        import genshi.template
        args = dict(source=src, )

        if filename:
            args['loader'] = genshi.template.TemplateLoader([
                genshi.template.loader.directory(directory),
            ])

        tmpl = genshi.template.MarkupTemplate(**args)
        return lambda kwargs: Markup(''.join(
            tmpl.generate(**kwargs).serialize('xhtml')))

    elif engine_name == 'jinja':
        import jinja2
        from jinja_util import htmlbools
        env = jinja2.environment.Environment(autoescape=True)
        env.filters['htmlbools'] = htmlbools
        tmpl = env.from_string(src, template_class=jinja2.Template)
        tmpl.filename = filename
        return lambda kwargs: Markup(tmpl.render(**kwargs))

    elif engine_name == 'kajiki':
        import kajiki
        tmpl = kajiki.XMLTemplate(src, filename=filename)
        return lambda kwargs: Markup(tmpl(kwargs).render())

    elif engine_name == 'chameleon':
        import chameleon
        tmpl = chameleon.PageTemplate(src, filename=filename)
        return lambda kwargs: Markup(tmpl.render(**kwargs).strip())

    raise NotImplementedError("Unhandled engine")
Exemplo n.º 2
0
 def get_template(self, template_name):
     try:
         template = self._loader[template_name]
     except KeyError:
         raise TemplateNotFound(template_name)
     if isinstance(template, str):
         template = chameleon.PageTemplate(template)
     return template
Exemplo n.º 3
0
async def test_func(aiohttp_client):
    @aiohttp_tal.template('tmpl.pt')
    async def func(request):
        return {'head': 'HEAD', 'text': 'text'}

    template = '<html><body><h1>${head}</h1>${text}</body></html>'
    app = web.Application()
    aiohttp_tal.setup(app,
                      loader={'tmpl.pt': chameleon.PageTemplate(template)})

    app.router.add_route('*', '/', func)

    client = await aiohttp_client(app)

    resp = await client.get('/')
    assert 200 == resp.status
    txt = await resp.text()
    assert '<html><body><h1>HEAD</h1>text</body></html>' == txt
Exemplo n.º 4
0
def get_chapter_content(times_list, params):

    edition = {
        'default': 1,
        'oc': 1 if params['op'] or params['ed'] else 0,
        'uid': str(time.time()).replace('.', '')
    }

    if params.get('avs_chapters'):
        frames = params['avs_chapters']['frames']
        params['avs_chapters']['times'] = list()

        for frame in frames:
            start = float('%.3f' % (frame[0] / params['frame_rate']))
            end = float('%.3f' % (frame[1] / params['frame_rate']))
            params['avs_chapters']['times'].append((start, end))

    atoms = list()
    names, order = get_names_and_order(times_list, params)
    last_timestamp = None
    print(names)
    print(order)
    print('#' * 50)

    for num, item in enumerate(order):

        atom = dict()
        atom['uid'] = str(time.time() + num).replace('.', '')
        atom['hidden'] = 0
        atom['enabled'] = 1

        if isinstance(item, dict):
            atom['start'] = '%02d:%02d:%02d.%09d' % (0, 0, 0, 0)
            atom['end'] = item['duration']
            atom['suid'] = item['suid']

        elif isinstance(item, (tuple, list)):
            item = tuple([float('%.03f' % (value)) for value in item])

            if num > 0:
                if isinstance(order[num - 1], dict) or \
                  abs(order[num - 1][1] - item[0]) > 1:
                    continuous = False
                else:
                    continuous = True
                    continuity_offset = item[0] - order[num - 1][1]

            print(item, end=' -> ')

            if last_timestamp:
                diff = item[1] - item[0]

                if not continuous:
                    if num <= 2:
                        calculated_start = last_timestamp + 1 / params[
                            'frame_rate']
                    elif num > 2:
                        calculated_start = last_timestamp + 2 / params[
                            'frame_rate']

                    calculated_end = calculated_start + diff
                else:
                    calculated_start = last_timestamp
                    calculated_end = calculated_start + diff + continuity_offset

                item = (float('%.3f' % (calculated_start)),
                        float('%.3f' % (calculated_end)))

            print(item)
            atom['start'] = str(
                timedelta(seconds=int(str(item[0]).split('.')[0]),
                          milliseconds=int(
                              str(item[0]).split('.')[1].ljust(3, '0'))))

            atom['end'] = str(
                timedelta(seconds=int(str(item[1]).split('.')[0]),
                          milliseconds=int(
                              str(item[1]).split('.')[1].ljust(3, '0'))))

            last_timestamp = item[1]

        atom['ch-string'] = names[num]
        atoms.append(atom)

    template = chameleon.PageTemplate(CH_TEMPLATE_STRING)
    request = {'edition': edition, 'atoms': atoms}
    response = template(**request)

    return response
Exemplo n.º 5
0
class DaycareServicesWidget(object):

    template = chameleon.PageTemplate("""
        <table class="daycare-services">
            <thead>
                <tr>
                    <th></th>
                    <th tal:repeat="service this.services.available.values()">
                        <div class="daycare-services-title">
                            ${service.title}
                        </div>
                        <div class="daycare-services-percentage">
                            ${service.percentage}%
                        </div>
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr tal:repeat="day this.days">
                    <th>
                        <strong class="show-for-small-only">
                            ${this.day_label(day)[:2]}
                        </strong>
                        <strong class="show-for-medium-up">
                            ${this.day_label(day)}
                        </strong>
                    </th>
                    <td tal:repeat="svc this.services.available.values()">
                        <label>
                            <input
                                type="checkbox"

                                id="${svc.id}-${day}"
                                name="${this.field.name}"
                                value="${svc.id}-${day}"

                                tal:attributes="
                                    checked this.is_selected(svc, day)
                                "
                            />
                        </label>
                    </td>
                </tr>
            </tbody>
        </table
    """)

    def __call__(self, field, **kwargs):
        self.field = field
        self.services = field.services

        return HTMLString(self.template.render(this=self))

    def is_selected(self, service, day):
        return self.services.is_selected(service.id, day)

    def day_label(self, day):
        return self.field.meta.request.translate(SERVICE_DAYS_LABELS[day])

    @property
    def days(self):
        days = OrderedSet()

        for service in self.services.available.values():
            for day in service.days:
                days.add(day)

        return days