Exemple #1
0
    def get_value(self, cr, uid, object, message=None, context=None):

        if message is None:
            message = {}
        if message:
            try:
                from mako.template import Template as MakoTemplate
                message = tools.ustr(message)
                env = {
                    'user':
                    self.pool.get('res.users').browse(cr,
                                                      uid,
                                                      uid,
                                                      context=context),
                    'db':
                    cr.dbname
                }
                templ = MakoTemplate(message, input_encoding='utf-8')
                reply = MakoTemplate(message).render_unicode(
                    object=object,
                    peobject=object,
                    env=env,
                    format_exceptions=True)
                return reply or False
            except Exception:
                logging.exception("Can't render %r", message)
                return u""
        else:
            return message
Exemple #2
0
def get_value(cursor, user, recid, message=None, template=None, context=None):
    """
    Evaluates an expression and returns its value
    @param cursor: Database Cursor
    @param user: ID of current user
    @param recid: ID of the target record under evaluation
    @param message: The expression to be evaluated
    @param template: BrowseRecord object of the current template
    @param context: Open ERP Context
    @return: Computed message (unicode) or u""
    """
    pool = pooler.get_pool(cursor.dbname)
    if message is None:
        message = {}
    #Returns the computed expression
    if message:
        try:
            message = tools.ustr(message)
            object = pool.get(template.model_int_name).browse(cursor, user, recid, context)
            env = {
                'user':pool.get('res.users').browse(cursor, user, user, context),
                'db':cursor.dbname,
            }
            templ = MakoTemplate(message, input_encoding='utf-8')
            reply = MakoTemplate(message).render_unicode(object=object,
                                                         peobject=object,
                                                         env=env,
                                                         format_exceptions=True)
            return reply or False
        except Exception:
            return u""
    else:
        return message
    def studio_view(self, context):
        """
        Render a form for editing this XBlock
        """
        fragment = Fragment()
        static_content = ResourceLoader(
            'common.djangoapps.pipeline_mako').load_unicode(
                'templates/static_content.html')
        render_react = MakoTemplate(static_content,
                                    default_filters=[]).get_def('renderReact')
        react_content = render_react.render(
            component="LibrarySourcedBlockPicker",
            id="library-sourced-block-picker",
            props={
                'selectedXblocks': self.source_block_ids,
            })
        fragment.content = loader.render_django_template(
            'templates/library-sourced-block-studio-view.html', {
                'react_content': react_content,
                'save_url': self.runtime.handler_url(self,
                                                     'submit_studio_edits'),
            })

        fragment.add_javascript_url(
            self.runtime.local_resource_url(
                self, 'public/js/library_source_block.js'))
        fragment.initialize_js('LibrarySourceBlockStudioView')

        return fragment
Exemple #4
0
    def render_template(self, cr, uid, template, model, res_id, context=None):
        result = super(email_template,
                       self).render_template(cr, uid, template, model, res_id,
                                             context)
        if (model == 'newsletter.newsletter' and res_id
                and context.get('newsletter_res_id')):

            newsletter = self.pool.get(model).browse(cr,
                                                     uid,
                                                     res_id,
                                                     context=context)
            user = self.pool.get('res.users').browse(cr,
                                                     uid,
                                                     uid,
                                                     context=context)

            result = MakoTemplate(result).render_unicode(
                object=self.pool.get(newsletter.type_id.model.model).browse(
                    cr, uid, context.get('newsletter_res_id'), context),
                user=user,
                # context kw would clash with mako internals
                ctx=context,
                quote=quote,
                format_exceptions=True)

        return result
Exemple #5
0
        def get_template(self, uri, kwargs=None):

            filepath = join(self.templates_directory, uri + '.mako')
            if not exists(filepath):
                raise IOError("Cannot find template %s.mako" % uri)

            template_time = getmtime(filepath)

            if ((template_time <= self._template_mtime_data.get(uri, 0))
                    and ((uri, kwargs) in self._template_cache)):
                return self._template_cache[(uri, kwargs)]

            if kwargs:
                _template_args = self.template_args.copy()
                _template_args.update(dict(kwargs))
            else:
                _template_args = self.template_args

            template = MakoTemplate(uri=uri,
                                    filename=filepath,
                                    lookup=self,
                                    **_template_args)

            self._template_cache[(uri, kwargs)] = template
            self._template_mtime_data[uri] = template_time

            return template
Exemple #6
0
 def render(self,
            cr,
            uid,
            id,
            object,
            reference,
            currency,
            amount,
            context=None,
            **kwargs):
     """ Renders the form template of the given acquirer as a mako template  """
     if not isinstance(id, (int, long)):
         id = id[0]
     this = self.browse(cr, uid, id)
     if context is None:
         context = {}
     try:
         i18n_kind = _(object._description
                       )  # may fail to translate, but at least we try
         result = MakoTemplate(this.form_template).render_unicode(
             object=object,
             reference=reference,
             currency=currency,
             amount=amount,
             kind=i18n_kind,
             quote=quote,
             # context kw would clash with mako internals
             ctx=context,
             format_exceptions=True)
         return result.strip()
     except Exception:
         _logger.exception(
             "failed to render mako template value for payment.acquirer %s: %r",
             this.name, this.form_template)
         return
Exemple #7
0
    def render_template(self, cr, uid, template, model, res_id, context=None):
        """Render the given template text, replace mako expressions ``${expr}``
           with the result of evaluating these expressions with
           an evaluation context containing:

                * ``user``: browse_record of the current user
                * ``object``: browse_record of the document record this mail is
                              related to
                * ``context``: the context passed to the mail composition wizard

           :param str template: the template text to render
           :param str model: model name of the document record this mail is related to.
           :param int res_id: id of the document record this mail is related to.
        """
        if not template: return u""
        if context is None:
            context = {}
        try:
            template = tools.ustr(template)
            record = None
            if res_id:
                record = self.pool.get(model).browse(cr, uid, res_id, context=context)
            user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
            result = MakoTemplate(template).render_unicode(object=record,
                                                           user=user,
                                                           # context kw would clash with mako internals
                                                           ctx=context,
                                                           quote=quote,
                                                           format_exceptions=True)
            if result == u'False':
                result = u''
            return result
        except Exception:
            logging.exception("failed to render mako template value %r", template)
            return u""
Exemple #8
0
def render_mako(source_text, source_path, vars):
    assert MakoTemplate, "Mako is not installed"
    try:
        return MakoTemplate(text=source_text,
                            filename=source_path).render(**vars)
    except MakoException as error:
        raise errors.TemplateError("{0}: {1}: {2}".format(
            source_path, error.__class__.__name__, error))
Exemple #9
0
 def __init__(self, *args, **kwargs):
     """Overrides base __init__ to provide django variable overrides"""
     self.engine = kwargs.pop('engine', engines[Engines.MAKO])
     if len(args) and isinstance(args[0], MakoTemplate):
         self.mako_template = args[0]
     else:
         kwargs['lookup'] = LOOKUP['main']
         self.mako_template = MakoTemplate(*args, **kwargs)
Exemple #10
0
    def from_string(self, template_code):
        """
        Compiles the template code and return the compiled version.

        :param template_code: Textual template source.
        :return: Returns a compiled Mako template.
        """
        return MakoTemplate(template_code, lookup=self.lookup)
 def map(self, request, context=None):
     """
     lms视图
     """
     html = self.resource_string("static/html/map.html")
     content = MakoTemplate(html).render(display_name=self.display_name,
                                         data=self.json_data,
                                         offset=self.offset)
     return self.html_response(content)
Exemple #12
0
 def render_mako_template(self, template_path, context=None):
     """
     Evaluate a mako template by resource path, applying the provided context
     """
     context = context or {}
     template_str = self.load_unicode(template_path)
     lookup = MakoTemplateLookup(directories=[pkg_resources.resource_filename(self.module_name, '')])
     template = MakoTemplate(template_str, lookup=lookup)
     return template.render(**context)
 def setUp(self):
     """
     Load the template under test.
     """
     capa_path = capa.__path__[0]
     self.template_path = os.path.join(capa_path, 'templates',
                                       self.TEMPLATE_NAME)
     with open(self.template_path) as f:
         self.template = MakoTemplate(f.read())
Exemple #14
0
 def studio_view(self, context=None):
     html = self.resource_string("static/html/studio.html")
     frag = Fragment()
     context = {'block': self}
     frag.add_content(MakoTemplate(text=html).render_unicode(**context))
     frag.add_css(self.resource_string("static/css/scormxblock.css"))
     frag.add_javascript(self.resource_string("static/js/src/studio.js"))
     frag.initialize_js('ScormStudioXBlock')
     return frag
 def setUp(self):
     """
     Load the template under test.
     """
     capa_path = capa.__path__[0]
     self.template_path = os.path.join(capa_path, 'templates',
                                       self.TEMPLATE_NAME)
     template_file = open(self.template_path)
     self.template = MakoTemplate(template_file.read())
     template_file.close()
Exemple #16
0
 def get_template(self, name, **kw):
     if self._lookup is None:
         self._lookup = TemplateLookup(directories=self.directories, **kw)
     try:
         return self._lookup.get_template('%s.%s' % (name, self.extension))
     except TopLevelLookupException:
         filename = os.path.join(MAKO_TEMPLATES, '%s.mako_tmpl' % name)
         if os.path.isfile(filename):
             template = TempitaTemplate.from_filename(filename)
             return MakoTemplate(template.substitute(template_engine='mako'), **kw)
Exemple #17
0
 def __init__(self, *args, **kwargs):
     """Overrides base __init__ to provide django variable overrides"""
     self.engine = kwargs.pop('engine', engines[Engines.MAKO])
     if kwargs.get('origin') is None:
         self.origin = Origin(UNKNOWN_SOURCE)
     if len(args) and isinstance(args[0], MakoTemplate):  # lint-amnesty, pylint: disable=len-as-condition
         self.mako_template = args[0]
     else:
         kwargs['lookup'] = LOOKUP['main']
         self.mako_template = MakoTemplate(*args, **kwargs)
 def editor(self, request, suffix=''):
     """
     新页面加载百度脑图编辑器
     """
     html = self.resource_string("static/html/editor.html")
     # 硬编码依赖cms url
     content = MakoTemplate(html).render(
         data=self.json_data,
         url=reverse("component_handler",
                     args=(self.scope_ids.usage_id, "save_map", "")))
     return self.html_response(content)
Exemple #19
0
def test_extract_def_source():
    src = """
        <%def name="add(varname)">
        ${varname} + ${num}
        </%def>

        <%def name='sub(varname, kwd=">")'>
        ${varname} - ${num}
        </%def>
    """

    def_src = _extract_def_source(src, 'add')
    template = MakoTemplate(def_src)
    assert 'add' in template.list_defs()
    assert 'sub' not in template.list_defs()

    def_src = _extract_def_source(src, 'sub')
    template = MakoTemplate(def_src)
    assert 'sub' in template.list_defs()
    assert 'add' not in template.list_defs()
Exemple #20
0
def render_mako_template(template_path, context={}):
    """
    Evaluate a mako template by resource path, applying the provided context
    """

    template_dir = pkg_resources.resource_filename('discussion_app',
                                                   'templates/discussion')
    lookup = MakoTemplateLookup(directories=[template_dir])

    template_str = load_resource(template_path)
    template = MakoTemplate(text=template_str, lookup=lookup)
    return template.render_unicode(**context)
Exemple #21
0
    def setUp(self):
        """
        Load the template under test.
        """
        super(TemplateTestCase, self).setUp()
        capa_path = capa.__path__[0]
        self.template_path = os.path.join(capa_path, 'templates',
                                          self.TEMPLATE_NAME)
        with open(self.template_path) as f:
            self.template = MakoTemplate(f.read())

        self.context = {}
Exemple #22
0
def patch_one_script(raw_path, patched_path, parameters):
    """
    Apply mako dict to one script.
    """
    template = MakoTemplate(filename=raw_path, input_encoding="utf-8")
    try:
        with open(patched_path, "w") as f:
            f.write(template.render(parameters=parameters))
    except (KeyError):
        # nothing to patch, copy the file anyway.
        shutil.copy(raw_path, patched_path)
    return True
Exemple #23
0
    def merge_message(self, cr, uid, keystr, action, context):
        obj_pool = self.pool.get(action.model_id.model)
        id = context.get('active_id')
        obj = obj_pool.browse(cr, uid, id)

        message = MakoTemplate(keystr).render_unicode(object=obj,
                                                      context=context,
                                                      time=time)
        if message == keystr:
            message = super(action_server,
                            self).merge_message(cr, uid, keystr, action,
                                                context)
        return message
Exemple #24
0
 def studio_view(self, context=None):
     html = self.resource_string("static/html/studio.html")
     frag = Fragment()
     file_uploaded_date = get_default_time_display(
         self.file_uploaded_date) if self.file_uploaded_date else ''
     context = {'block': self, 'file_uploaded_date': file_uploaded_date}
     frag.add_content(MakoTemplate(text=html).render_unicode(**context))
     frag.add_css(self.resource_string("static/css/scormxblock.css"))
     frag.add_javascript(self.resource_string("static/js/src/studio.js"))
     frag.add_javascript_url(
         self.runtime.local_resource_url(self,
                                         'public/jquery.fileupload.js'))
     frag.initialize_js('ScormStudioXBlock')
     return frag
    def get_value(self, cursor, user, recid, message=None, template=None, context=None):
        """
        Evaluates an expression and returns its value
        @param cursor: Database Cursor
        @param user: ID of current user
        @param recid: ID of the target record under evaluation
        @param message: The expression to be evaluated
        @param template: BrowseRecord object of the current template
        @param context: Open ERP Context
        @return: Computed message (unicode) or u""
        """
        if message is None:
            message = {}
        #Returns the computed expression
        if message:
            try:
                message = tools.ustr(message)
                if not context:
                    context = {}
                ctx = context.copy()
                ctx.update({'browse_reference': True})
                object = self.pool.get(
                    template.object_name.model
                ).browse(cursor, user, recid, ctx)
                env = context.copy()
                env.update({
                    'user': self.pool.get('res.users').browse(cursor, user, user,
                                                        context),
                    'db': cursor.dbname
                })

                templ = MakoTemplate(message, input_encoding='utf-8')
                extra_render_values = env.get('extra_render_values', {}) or {}
                values = {
                    'object': object,
                    'peobject': object,
                    'env': env,
                    'format_exceptions': True,
                }
                values.update(extra_render_values)
                reply = templ.render_unicode(**values)

                return reply or False
            except Exception:
                import traceback
                traceback.print_exc()
                return u""
        else:
            return message
Exemple #26
0
    def message_quote_context(self, cr, uid, id, context=None, limit=3, add_original=False):
        """
            1. message.parent_id = False: new thread, no quote_context
            2. get the lasts messages in the thread before message
            3. get the message header
            4. add an expandable between them

            :param dict quote_context: options for quoting
            :return string: html quote
        """
        add_expandable = False

        message = self.browse(cr, uid, id, context=context)
        if not message.parent_id:
            return ''
        context_ids = self.search(cr, uid, [
            ('parent_id', '=', message.parent_id.id),
            ('id', '<', message.id),
            ], limit=limit, context=context)

        if len(context_ids) >= limit:
            add_expandable = True
            context_ids = context_ids[0:-1]

        context_ids.append(message.parent_id.id)
        context_messages = self.browse(cr, uid, context_ids, context=context)
        header_message = context_messages.pop()

        try:
            if not add_original:
                message = False
            result = MakoTemplate(self.MAIL_TEMPLATE).render_unicode(message=message,
                                                        context_messages=context_messages,
                                                        header_message=header_message,
                                                        add_expandable=add_expandable,
                                                        # context kw would clash with mako internals
                                                        ctx=context,
                                                        format_exceptions=True)
            result = result.strip()
            return result
        except Exception:
            _logger.exception("failed to render mako template for quoting message")
            return ''
        return result
Exemple #27
0
 def __init__(self, filename, subject=None, pre_inline_css=False):
     """
     Params:
         pre_inline_css: 预处理CSS内联,提高HTML渲染速度。要求模板不能含有任何循环和条件样式。
     """
     filepath = os.path.join(BASE_DIR, 'rssant/templates/email', filename)
     self.filepath = filepath
     with open(filepath) as f:
         html = f.read()
     self.pre_inline_css = pre_inline_css
     if pre_inline_css:
         html = pynliner.fromString(html)
     if filename.endswith('.mako'):
         self.is_mako = True
         self.html_template = MakoTemplate(html)
     else:
         self.is_mako = False
         self.html_template = Template(html)
     self.subject = subject or ''
Exemple #28
0
        def get_template(self, uri, kwargs=None):

            if (uri, kwargs) in self._template_cache:
                return self._template_cache[(uri, kwargs)]

            filepath = join(self.templates_directory, uri + '.mako')
            if not exists(filepath):
                raise IOError("Cannot find template %s.mako" % uri)

            if kwargs:
                _template_args = self.template_args.copy()
                _template_args.update(dict(kwargs))
            else:
                _template_args = self.template_args

            template = MakoTemplate(uri=uri,
                                    filename=filepath,
                                    lookup=self,
                                    **_template_args)

            return self._template_cache.setdefault((uri, kwargs), template)
Exemple #29
0
 def from_string(self, template_code):
     try:
         return Template(MakoTemplate(template_code, lookup=self.lookup), [])
     except mako_exceptions.SyntaxException as e:
         raise TemplateSyntaxError(e.args)
Exemple #30
0
        start_response(*RESPONSE_500)
        if isinstance(response, unicode):
            response = response.encode('utf-8')
        return [response]


handle_http_request.router = None

# ------------------------------------------------------------------------------
# Template Error Handling
# ------------------------------------------------------------------------------

PlainErrorTemplate = MakoTemplate("""
Traceback (most recent call last):
% for (filename, lineno, function, line) in traceback.traceback:
  File "${filename}", line ${lineno}, in ${function or '?'}
    ${line | trim}
% endfor
${traceback.errorname}: ${traceback.message}
""")

HTMLErrorTemplate = MakoTemplate(r"""
<style type="text/css">
    .stacktrace { margin:5px 5px 5px 5px; }
    .highlight { padding:0px 10px 0px 10px; background-color:#9F9FDF; }
    .nonhighlight { padding:0px; background-color:#DFDFDF; }
    .sample { padding:10px; margin:10px 10px 10px 10px; font-family:monospace; }
    .sampleline { padding:0px 10px 0px 10px; }
    .sourceline { margin:5px 5px 10px 5px; font-family:monospace;}
    .location { font-size:80%; }
</style>
<%