Esempio n. 1
0
def render_html_str(s, context=None, request=None):
    """ Use DjangoTemplates() to render a template string.
        Returns the rendered content str on success.
    """
    template = DjangoTemplates(settings.DJANGO_TEMPLATES_OPTS).from_string(s)
    try:
        content = template.render(context=context or {}, request=request)
    except Exception as ex:
        # For trimming the template string, for logging.
        max_content_len = 45
        log.error(
            '\n'.join((
                'Cannot render template str: {s}{ellipses}',
                '    Context: {context}',
                '    Request: {request}',
                '      Error: ({errtype}) {errmsg}',
            )).format(
                s=s[:max_content_len],
                ellipses='...' if len(s) > max_content_len else '',
                context=context,
                request=request,
                errtype=type(ex).__name__,
                errmsg=ex,
            )
        )
        return ''
    return content
Esempio n. 2
0
def retrieve_template(template_id):
    request = get_current_request()
    if is_github_remote_enabled(request):
        template_slug = template_id
        variables = json.loads(
            get_github_repo(request).get_file_contents('/' + template_slug + '.defaults').decoded_content.decode())
    else:
        template_db = Template.objects.get(pk=int(template_id))
        template_slug = template_db.slug

        variables = {var["name"]: var["initial"] for var in parse_vars(template_db.variables)}

    engine = DjangoTemplates(
            {
                'NAME': 'mail',
                'APP_DIRS': False,
                'DIRS': [],
                'OPTIONS': {
                    'loaders': [
                        'events.loaders.MyLoader',
                    ],
                },
            })
    template = engine.get_template(template_slug)
    return template, variables
Esempio n. 3
0
    def test_context_has_priority_over_template_context_processors(self):
        # See ticket #23789.
        engine = DjangoTemplates(
            {"DIRS": [], "APP_DIRS": False, "NAME": "django", "OPTIONS": {"context_processors": [test_processor_name]}}
        )

        template = engine.from_string("{{ processors }}")
        request = RequestFactory().get("/")

        # Check that context processors run
        content = template.render({}, request)
        self.assertEqual(content, "yes")

        # Check that context overrides context processors
        content = template.render({"processors": "no"}, request)
        self.assertEqual(content, "no")
Esempio n. 4
0
 def test_render_requires_dict(self):
     """django.Template.render() requires a dict."""
     engine = DjangoTemplates({
         'DIRS': [],
         'APP_DIRS': False,
         'NAME': 'django',
         'OPTIONS': {},
     })
     template = engine.from_string('')
     context = Context()
     request_context = RequestContext(RequestFactory().get('/'), {})
     msg = 'context must be a dict rather than Context.'
     with self.assertRaisesMessage(TypeError, msg):
         template.render(context)
     msg = 'context must be a dict rather than RequestContext.'
     with self.assertRaisesMessage(TypeError, msg):
         template.render(request_context)
Esempio n. 5
0
    def test_context_has_priority_over_template_context_processors(self):
        # See ticket #23789.
        engine = DjangoTemplates({
            'DIRS': [],
            'APP_DIRS': False,
            'NAME': 'django',
            'OPTIONS': {
                'context_processors': [test_processor_name],
            },
        })

        template = engine.from_string('{{ processors }}')
        request = RequestFactory().get('/')

        # Check that context processors run
        content = template.render({}, request)
        self.assertEqual(content, 'yes')

        # Check that context overrides context processors
        content = template.render({'processors': 'no'}, request)
        self.assertEqual(content, 'no')