コード例 #1
0
def get_context():
    if engines is not None:
        context = Context()
        context.template = Template('')
        return context
    else:
        return Context()
コード例 #2
0
    def test_include_error08(self):
        t = get_template('include-error08')

        if settings.TEMPLATE_DEBUG:
            with self.assertRaises(TemplateSyntaxError):
                t.render(Context())
        else:
            self.assertEqual(t.render(Context()), '')
コード例 #3
0
    def test_include04(self):
        template = get_template('include04')

        if settings.TEMPLATE_DEBUG:
            with self.assertRaises(TemplateDoesNotExist):
                template.render(Context({}))
        else:
            output = template.render(Context({}))
            self.assertEqual(output, "ab")
コード例 #4
0
    def render(self, context):
        # our main context
        storage = Context()

        # stash the whole context if needed
        if getattr(settings, 'PHASED_KEEP_CONTEXT', False):
            storage.update(flatten_context(context))

        # but check if there are variables specifically wanted
        for var_name in self.var_names:
            if var_name[0] in ('"', "'") and var_name[-1] == var_name[0]:
                var_name = var_name[1:-1]
            try:
                storage[var_name] = Variable(var_name).resolve(context)
            except VariableDoesNotExist:
                raise TemplateSyntaxError(
                    '"phased" tag got an unknown variable: %r' % var_name)

        storage = backup_csrf_token(context, storage)

        # lastly return the pre phased template part
        return u'%(delimiter)s%(content)s%(pickled)s%(delimiter)s' % {
            'content': self.content,
            'delimiter': settings.PHASED_SECRET_DELIMITER,
            'pickled': pickle_context(storage),
        }
コード例 #5
0
ファイル: tests.py プロジェクト: skyride/django-apptemplates
def test_cached():
    """
    Test that the template still works when the cached loader is being used.
    """
    c = Context()
    t = Template('{% extends "admin:admin/base.html" %}')
    t.render(c)
コード例 #6
0
ファイル: tests.py プロジェクト: skyride/django-apptemplates
def test_render():
    """
    Test-drive the apptemplate code base by rendering a template.
    """
    c = Context()
    t = Template('{% extends "admin:admin/base.html" %}')
    t.render(c)
コード例 #7
0
def render(template_name, context=None):
    if context is None:
        context = {}

    t = get_template(template_name)
    with translation.override(context.get('LANGUAGE_CODE', 'en-us')):
        return t.render(Context(context))
コード例 #8
0
def api_contact_send(request):
    if request.is_ajax() or request.method == 'POST':
        contact_form = ContactForm(data=request.POST)
        if contact_form.is_valid():
            email_to = config.EMAIL
            email_from = settings.DEFAULT_FROM_EMAIL
            message = contact_form.cleaned_data['message']
            name = contact_form.cleaned_data['name']
            email_or_phone = contact_form.cleaned_data['email_or_phone']
            email_subject = force_text(strings.CONTACT_EMAIL_SUBJECT %
                                       {'person_name': name})
            email = EmailMultiAlternatives(
                email_subject,
                Template(strings.CONTACT_EMAIL_BODY).render(
                    Context({
                        'name': name,
                        'email': email_or_phone,
                        'message': message,
                    })), email_from, [email_to], None, None, None, None, None,
                None)
            email.send()
            return render(request, 'contact/contact_response.html', {})
        else:
            return render(request, 'contact/contact.html',
                          {'contact_form': contact_form})
コード例 #9
0
def render_to_string(template_name,
                     dictionary=None,
                     context_instance=None,
                     dirs=None):
    """
    Loads the given template_name and renders it with the given dictionary as
    context. The template_name may be a string to load a single template using
    get_template, or it may be a tuple to use select_template to find one of
    the templates in the list. Returns a string.
    """
    if isinstance(template_name, (list, tuple)):
        t = select_template(template_name, dirs)
    else:
        t = get_template(template_name, dirs)
    if not context_instance:
        # Django < 1.8 accepted a Context in `dictionary` even though that's
        # unintended. Preserve this ability but don't rewrap `dictionary`.
        if isinstance(dictionary, Context):
            return t.render(dictionary)
        else:
            return t.render(Context(dictionary))
    if not dictionary:
        return t.render(context_instance)
    # Add the dictionary to the context stack, ensuring it gets removed again
    # to keep the context_instance in the same state it started in.
    with context_instance.push(dictionary):
        return t.render(context_instance)
コード例 #10
0
ファイル: test_utils.py プロジェクト: 498330580/yaoling-web
def test_custom_bound_field():
    from django.forms.boundfield import BoundField

    extra = 'xyxyxyxyxyx'

    class CustomBoundField(BoundField):
        @property
        def auto_id(self):
            return extra

    class MyCharField(forms.CharField):
        def get_bound_field(self, form, field_name):
            return CustomBoundField(form, self, field_name)

    class MyForm(forms.Form):
        f = MyCharField()

        def __init__(self, *args, **kwargs):
            super(MyForm, self).__init__(*args, **kwargs)
            self.helper = FormHelper()
            self.helper.layout = Layout('f')

    template = Template('{% load crispy_forms_tags %}\n{% crispy form "bootstrap3" %}')
    rendered = template.render(Context({'form': MyForm(data={'f': 'something'})}))

    assert extra in rendered
コード例 #11
0
    def form_valid(self, form):
        form.save()
        messages.success(self.request, _('Successfully saved changes.'))

        if form.cleaned_data['send_login_data']:
            t = template.loader.get_template(
                'booktypecontrol/password_changed_email.html')
            content = t.render(
                Context({
                    "username": self.object.username,
                    "password": form.cleaned_data['password2'],
                    "short_message": form.cleaned_data['short_message']
                }))

            msg = EmailMultiAlternatives(_('Your password was changed'),
                                         content, settings.DEFAULT_FROM_EMAIL,
                                         [self.object.email])
            msg.attach_alternative(content, "text/html")
            try:
                msg.send(fail_silently=False)
            except Exception as e:
                logger.error(
                    '[CCENTER] Unable to send email to %s after password was changed, msg: %s'
                    % (self.object.email, e))

        return super(FormView, self).form_valid(form)
コード例 #12
0
    def test_basic_syntax20b(self):
        """
        Don't silence a TypeError if it was raised inside a callable.
        """
        template = self.engine.get_template('basic-syntax20b')

        with self.assertRaises(TypeError):
            template.render(Context({'var': SomeClass()}))
コード例 #13
0
 def render(self, context):
     values = dict([(key, val.resolve(context))
                    for key, val in self.extra_context.iteritems()])
     if self.isolated_context:
         return self.nodelist.render(Context(values))
     context.update(values)
     output = self.nodelist.render(context)
     context.pop()
     return output
コード例 #14
0
    def setUp(self):
        # Every test needs access to the request factory.
        factory = RequestFactory()

        self.context = Context({
            'request': factory.get('/data/test'),
            'var1': 1,
            'var2': 2
        })
コード例 #15
0
 def render_error(self, package_type, package_name, e):
     return render_to_string(
         'pipeline/compile_error.html',
         Context({
             'package_type': package_type,
             'package_name': package_name,
             'command': subprocess.list2cmdline(e.command),
             'errors': e.error_output,
         }))
コード例 #16
0
    def setUp(self):
        # Every test needs access to the request factory.
        factory = RequestFactory()

        self.context = Context({
            "request": factory.get("/data/test"),
            "var1": 1,
            "var2": 2
        })
コード例 #17
0
    def test_include_error10(self):
        c = Context({'failed_include': 'include-fail2'})
        t = get_template('include-error10')

        if settings.TEMPLATE_DEBUG:
            with self.assertRaises(TemplateSyntaxError):
                t.render(c)
        else:
            self.assertEqual(t.render(c), '')
コード例 #18
0
    def test_include_error09(self):
        c = Context({'failed_include': 'include-fail1'})
        t = get_template('include-error09')

        if settings.TEMPLATE_DEBUG:
            with self.assertRaises(RuntimeError):
                t.render(c)
        else:
            self.assertEqual(t.render(c), '')
コード例 #19
0
ファイル: test_middleware.py プロジェクト: fido20/django-text
 def process_template_response(self, string_template, user=None):
     request = HttpRequest()
     request.user = user
     context = Context({'request': request})
     template = BackendTemplate(Template(string_template).render(context))
     response = SimpleTemplateResponse(template, context)
     response.content = string_template
     mw = ToolbarMiddleware()
     return mw.process_response(request, response).render()
コード例 #20
0
def loremi(count, method, random=False):
    from django.template.base import Context, Token, Parser, TOKEN_TEXT
    from django.template.defaulttags import lorem
    c = Context()
    lorem_str = "lorem %s %s" % (count, method)
    if random:
        lorem_str += " random"
    t = Token(TOKEN_TEXT, lorem_str)
    p = Parser(t)
    return lorem(p, t).render(c)
コード例 #21
0
ファイル: test_middleware.py プロジェクト: fido20/django-text
 def process_template_response(self, string_template):
     settings.TOOLBAR_INSTANT_UPDATE = False
     request = HttpRequest()
     context = Context({'request': request})
     node = Template(string_template).render(context)
     template = BackendTemplate(node)
     response = SimpleTemplateResponse(template, context)
     response.content = node
     mw = TextMiddleware()
     return mw.process_response(request, response).render()
コード例 #22
0
ファイル: tests.py プロジェクト: neoguojing/cloudServer
    def test_load_template(self):
        app_namespace_loader = Loader(Engine())
        app_directory_loader = app_directories.Loader(Engine())

        template_directory = app_directory_loader.load_template(
            'admin/base.html')[0]
        template_namespace = app_namespace_loader.load_template(
            'admin:admin/base.html')[0]
        context = Context({})
        self.assertEquals(template_directory.render(context),
                          template_namespace.render(context))
コード例 #23
0
ファイル: tests.py プロジェクト: neoguojing/cloudServer
 def multiple_extend_empty_namespace(self):
     context = Context({})
     template = Template(self.template_extend % {
         'app': 'top-level'
     }).render(context)
     previous_app = ''
     for test_app in ['top-level'] + self.apps:
         self.assertTrue(test_app in template)
         if previous_app:
             self.assertTrue(
                 template.index(test_app) > template.index(previous_app))
         previous_app = test_app
コード例 #24
0
ファイル: tests.py プロジェクト: neoguojing/cloudServer
    def test_extend_empty_namespace(self):
        """
        Test that a ":" prefix (empty namespace) gets handled.
        """
        context = Context({})
        mark = 'Django administration'
        mark_title = '<title>APP NAMESPACE</title>'

        template_namespace = Template(
            '{% extends ":admin/base_site.html" %}'
            '{% block title %}APP NAMESPACE{% endblock %}').render(context)

        self.assertTrue(mark in template_namespace)
        self.assertTrue(mark_title in template_namespace)
コード例 #25
0
 def multiple_extend_empty_namespace(self):
     with self.settings(INSTALLED_APPS=self.apps +
                        ['django.contrib.admin']):  # Django 1.4 Fix
         context = Context({})
         template = Template(self.template_extend % {
             'app': 'top-level'
         }).render(context)
         previous_app = ''
         for test_app in ['top-level'] + self.apps:
             self.assertTrue(test_app in template)
             if previous_app:
                 self.assertTrue(
                     template.index(test_app) > template.index(previous_app)
                 )
             previous_app = test_app
コード例 #26
0
ファイル: models.py プロジェクト: rubickcz/django-pynotify
    def render(self, field, context):
        """
        Renders ``field`` using ``context``.
        """
        template_string = getattr(self, field) or ''

        if settings.TEMPLATE_TRANSLATE:
            template_string = _(template_string)

        if settings.TEMPLATE_CHECK:
            vars = re.findall(r'{{ ?([^\.}]+)[^}]*}}', template_string)
            for var in vars:
                if context.get(var) is None:
                    raise MissingContextVariableError(field, var)

        return Template(template_string).render(Context(context))
コード例 #27
0
    def as_html(self, request=None, type=None):
        """
        Returns the address as html.
        """
        templates = ["lfs/addresses/address_view.html"]
        if type:
            templates.insert(0, "lfs/addresses/%s_address_view.html" % type)

        if request:
            return render_to_string(templates, RequestContext(request, {
                "address": self,
            }))
        else:
            return render_to_string(templates, Context({
                "address": self,
            }))
コード例 #28
0
 def multiple_extend_empty_namespace(self, apps=None):
     if apps is None:
         apps = self.apps
     with self.settings(INSTALLED_APPS=apps):
         context = Context({})
         template = Template(self.template_extend % {
             'app': 'top-level'
         }).render(context)
         previous_app = ''
         for test_app in ['top-level'] + self.apps:
             self.assertTrue(test_app in template)
             if previous_app:
                 self.assertTrue(
                     template.index(test_app) > template.index(previous_app)
                 )
             previous_app = test_app
コード例 #29
0
ファイル: converter.py プロジェクト: jsaugustyn/Booktype
    def _write_style(self, book):
        """Creates style file.

        Style file will include default styling, theme styling and custom styling
        provided by the user.

        Created style file will be used by booktype2mpdf.php script
        to create final PDF file.

        :Args:
          - book: EPUB Book object
        """

        if 'settings' not in self.config:
            return

        css_style = create_default_style(self.config, self.name,
                                         self.get_extra_style(book))
        theme_style = u''

        if self.theme_name != '':
            theme_style = read_theme_style(self.theme_name, self.name)

            try:
                if self.theme_name == 'custom':
                    custom = self.config['theme'].pop('custom', '{}')
                    custom = json.loads(custom.encode('utf-8'))
                    self.config.update(custom)

                tmpl = Template(theme_style)
                ctx = Context(self.config)
                _style = tmpl.render(ctx)
                theme_style = _style
            except:
                logger.exception("Writing styles failed for `%s` theme." %
                                 self.theme_name)

        custom_style = self.config.get('settings', {}).get('styling', u'')

        # add css for fpi
        css_style += self._full_page_images_css

        f = codecs.open('{}/style.css'.format(self.sandbox_path), 'wt', 'utf8')
        f.write(css_style)
        f.write(theme_style)
        f.write(custom_style)
        f.close()
コード例 #30
0
ファイル: tests.py プロジェクト: crisish/blog
    def test_extend_and_override(self):
        """
        Here we simulate the existence of a template
        named admin/base_site.html on the filesystem
        overriding the title markup of the template.
        In this test we can view the advantage of using
        the app_namespace template loader.
        """
        context = Context({})
        mark = 'Django administration'
        mark_title = '<title>APP NAMESPACE</title>'

        template_directory = Template(
            '{% extends "admin/base.html" %}'
            '{% block title %}APP NAMESPACE{% endblock %}'
            ).render(context)

        template_namespace = Template(
            '{% extends "admin:admin/base_site.html" %}'
            '{% block title %}APP NAMESPACE{% endblock %}'
            ).render(context)

        self.assertTrue(mark in template_namespace)
        self.assertTrue(mark_title in template_namespace)
        self.assertTrue(mark not in template_directory)
        self.assertTrue(mark_title in template_directory)

        template_directory = Template(
            '{% extends "admin/base.html" %}'
            '{% load i18n %}'
            '{% block title %}APP NAMESPACE{% endblock %}'
            '{% block branding %}'
            '<h1 id="site-name">{% trans \'Django administration\' %}</h1>'
            '{% endblock %}'
            '{% block nav-global %}{% endblock %}'
            ).render(context)

        try:
            self.assertHTMLEqual(template_directory, template_namespace)
        except AssertionError:
            # This test will fail under Python > 2.7.3 and Django 1.4
            # - https://code.djangoproject.com/ticket/18027
            # - http://hg.python.org/cpython/rev/333e3acf2008/
            pass
        self.assertTrue(mark in template_directory)
        self.assertTrue(mark_title in template_directory)