예제 #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
예제 #2
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
예제 #3
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
예제 #4
0
 def test_dirs_pathlib(self):
     engine = DjangoTemplates({
         'DIRS':
         [Path(__file__).parent / 'templates' / 'template_backends'],
         'APP_DIRS':
         False,
         'NAME':
         'django',
         'OPTIONS': {},
     })
     template = engine.get_template('hello.html')
     self.assertEqual(template.render({'name': 'Joe'}), 'Hello Joe!\n')
예제 #5
0
파일: test_django.py 프로젝트: tbbug/django
 def test_dirs_pathlib(self):
     engine = DjangoTemplates({
         "DIRS":
         [Path(__file__).parent / "templates" / "template_backends"],
         "APP_DIRS":
         False,
         "NAME":
         "django",
         "OPTIONS": {},
     })
     template = engine.get_template("hello.html")
     self.assertEqual(template.render({"name": "Joe"}), "Hello Joe!\n")
예제 #6
0
    def _render(self, context):
        template_path = os.path.join(
            os.path.dirname(__file__), 'please-wait.html')
        template_code = open(template_path).read()

        # Normally, we would use template loaders, but could there be
        # interactions between the configs necessary here and in the parent app?
        engine = DjangoTemplates({
            'OPTIONS': {}, 'NAME': None, 'DIRS': [], 'APP_DIRS': []
        })
        # All the keys are required, but the values don't seem to matter.
        template = engine.from_string(template_code)

        return template.render(context)
예제 #7
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")
예제 #8
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)
예제 #9
0
 def test_debug_default_template_loaders(self):
     engine = DjangoTemplates({
         'DIRS': [],
         'APP_DIRS': True,
         'NAME': 'django',
         'OPTIONS': {}
     })
     self.assertEqual(engine.engine.loaders, self.default_loaders)
예제 #10
0
파일: test_django.py 프로젝트: tbbug/django
 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(self.request_factory.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)
예제 #11
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(self.request_factory.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)
예제 #12
0
파일: test_django.py 프로젝트: tbbug/django
 def test_debug_default_template_loaders(self):
     engine = DjangoTemplates({
         "DIRS": [],
         "APP_DIRS": True,
         "NAME": "django",
         "OPTIONS": {}
     })
     self.assertEqual(engine.engine.loaders, self.default_loaders)
예제 #13
0
    def get_online_content_template(self, template_name):
        # return an instance of Template
        # Template(contents, origin, origin.template_name, self.engine,)
        # contents is the content of the .html file
        # origin is an Origin instance
        # engine is a template engine
        # Template can be instantiated directly, only with contents

        # templates shipped with theme
        templates_base_dir = self.get_online_content_templates_path()

        # templates uploaded by user
        user_uploaded_templates_base_dir = self.get_user_uploaded_online_content_templates_path(
        )

        # check if template is shipped with the theme
        template_path = os.path.join(templates_base_dir, template_name)

        if not os.path.isfile(template_path):

            # if not check if the template was uploaded by the user
            template_path = os.path.join(user_uploaded_templates_base_dir,
                                         template_name)

            if not os.path.isfile(template_path):
                msg = 'Online Content Template %s does not exist. Tried: %s' % (
                    template_name, template_path)
                raise TemplateDoesNotExist(msg)

        params = {
            'NAME': 'OnlineContentEngine',
            #'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [templates_base_dir, user_uploaded_templates_base_dir],
            'APP_DIRS': False,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
                'loaders': [
                    'django.template.loaders.filesystem.Loader',
                ]
            },
        }
        engine = DjangoTemplates(params)

        with open(template_path, encoding=engine.engine.file_charset) as fp:
            contents = fp.read()

        # use the above engine with dirs
        template = Template(contents, engine=engine.engine)
        return template
예제 #14
0
def get_template():
    if this_module.template is None:
        template_path = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            'request_history.html'
        )
        with open(template_path) as template_file:
            this_module.template = Template(
                template_file.read(),
                engine=DjangoTemplates({'NAME': 'rh', 'DIRS': [], 'APP_DIRS': False, 'OPTIONS': {}}).engine
        )
    return this_module.template
예제 #15
0
파일: test_django.py 프로젝트: tbbug/django
    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 = self.request_factory.get("/")

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

        # Context overrides context processors
        content = template.render({"processors": "no"}, request)
        self.assertEqual(content, "no")
예제 #16
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')
예제 #17
0
def get_django_template_from_string(template_string):
    # We need to create an ad-hoc django templates backend
    # since we can't trust that the user's configuration
    # even includes one.  Using the "raw" `django.template.Template`
    # object does not work for reasons unknown (well, semi-unknown;
    # it just seems to have a slightly different API).
    from django.template.backends.django import DjangoTemplates
    return DjangoTemplates({
        'NAME': 'django-form-designer-renderer',
        'DIRS': [],
        'APP_DIRS': False,
        'OPTIONS': {},
    }).from_string(template_string)
    def _get_custom_engine(self, **options):
        options.setdefault('loaders', (
            'django.template.loaders.filesystem.Loader',
            'django.template.loaders.app_directories.Loader',
            'template_analyzer.tests.app_loader.Loader',
        ))

        from django.template.backends.django import DjangoTemplates
        return DjangoTemplates({
            'NAME': 'loader_test',
            'DIRS': (),
            'APP_DIRS': False,
            'OPTIONS': options,
        })
예제 #19
0
 def _get_custom_engine(self):
     from django.template.backends.django import DjangoTemplates
     return DjangoTemplates({
         'NAME': 'loader_test',
         'DIRS': (),
         'APP_DIRS': False,
         'OPTIONS': {
             'loaders': (
                 'django.template.loaders.filesystem.Loader',
                 'django.template.loaders.app_directories.Loader',
                 'template_analyzer.tests.app_loader.Loader',
             ),
         }
     })
예제 #20
0
    def _load_engine(self) -> None:
        """
        Creates the Django Engine instance that we use to get path from file name
        """
        try:
            from django.conf import settings

            obj = settings.TEMPLATES[0].copy()
            obj["NAME"] = "a"
            obj.pop("BACKEND")
            self.engine = DjangoTemplates(params=obj).engine
        except:
            print("Error loading engine. Probably will break.")
            pass
예제 #21
0
 def test_templatetag_discovery_import_error(self):
     """
     Import errors in tag modules should be reraised with a helpful message.
     """
     with self.assertRaisesMessage(
         InvalidTemplateLibrary,
         "ImportError raised when trying to load "
         "'template_backends.apps.importerror.templatetags.broken_tags'"
     ):
         DjangoTemplates({
             'DIRS': [],
             'APP_DIRS': False,
             'NAME': 'django',
             'OPTIONS': {},
         })
예제 #22
0
파일: test_django.py 프로젝트: tbbug/django
 def test_templatetag_discovery_import_error(self):
     """
     Import errors in tag modules should be reraised with a helpful message.
     """
     with self.assertRaisesMessage(
             InvalidTemplateLibrary,
             "ImportError raised when trying to load "
             "'template_backends.apps.importerror.templatetags.broken_tags'",
     ) as cm:
         DjangoTemplates({
             "DIRS": [],
             "APP_DIRS": False,
             "NAME": "django",
             "OPTIONS": {},
         })
     self.assertIsInstance(cm.exception.__cause__, ImportError)
예제 #23
0
    def test_builtins_discovery(self):
        engine = DjangoTemplates({
            'DIRS': [],
            'APP_DIRS': False,
            'NAME': 'django',
            'OPTIONS': {
                'builtins':
                ['template_backends.apps.good.templatetags.good_tags'],
            },
        })

        self.assertEqual(engine.engine.builtins, [
            'django.template.defaulttags',
            'django.template.defaultfilters',
            'django.template.loader_tags',
            'template_backends.apps.good.templatetags.good_tags',
        ])
예제 #24
0
class EventParticipationView(
    SoftLoginRequiredMixin, BaseEventDetailView,
):
    template_name = "events/participation.html"
    permission_required = ("events.view_event", "events.participate_online")
    permission_denied_message = _(
        "Vous devez être inscrit⋅e à l'événement pour accéder à cette page."
    )
    custom_template_engine = DjangoTemplates(
        {
            "APP_DIRS": False,
            "DIRS": [],
            "NAME": "ParticipationEngine",
            "OPTIONS": {"builtins": []},
        }
    )

    def get_context_data(self, **kwargs):
        if self.object.is_past():
            raise PermissionDenied("L'événement est terminé !")
        if not self.object.is_current():
            raise PermissionDenied("L'événement n'est pas encore commencé !")

        context_data = super().get_context_data(**kwargs)

        if context_data["rsvp"].jitsi_meeting is None:
            assign_jitsi_meeting(context_data["rsvp"])

        jitsi_fragment = loader.get_template("events/jitsi_fragment.html").render(
            {"jitsi_meeting": context_data["rsvp"].jitsi_meeting}
        )

        if self.object.participation_template:
            template = self.custom_template_engine.from_string(
                self.object.participation_template
            )
            context_data["content"] = template.render(
                {
                    "jitsi_video": jitsi_fragment,
                    "group_code": context_data["rsvp"].jitsi_meeting.room_name,
                }
            )
        else:
            context_data["content"] = jitsi_fragment

        return context_data
예제 #25
0
파일: test_django.py 프로젝트: tbbug/django
    def test_builtins_discovery(self):
        engine = DjangoTemplates({
            "DIRS": [],
            "APP_DIRS": False,
            "NAME": "django",
            "OPTIONS": {
                "builtins":
                ["template_backends.apps.good.templatetags.good_tags"],
            },
        })

        self.assertEqual(
            engine.engine.builtins,
            [
                "django.template.defaulttags",
                "django.template.defaultfilters",
                "django.template.loader_tags",
                "template_backends.apps.good.templatetags.good_tags",
            ],
        )
예제 #26
0
 def test_default_template_loaders(self):
     """The cached template loader is always enabled by default."""
     for debug in (True, False):
         with self.subTest(DEBUG=debug), self.settings(DEBUG=debug):
             engine = DjangoTemplates({
                 "DIRS": [],
                 "APP_DIRS": True,
                 "NAME": "django",
                 "OPTIONS": {}
             })
             self.assertEqual(
                 engine.engine.loaders,
                 [(
                     "django.template.loaders.cached.Loader",
                     [
                         "django.template.loaders.filesystem.Loader",
                         "django.template.loaders.app_directories.Loader",
                     ],
                 )],
             )
예제 #27
0
def get_djangotemplates_engines():
    """
    Create template engines from the parameters in the settings file.

    :returns: a list of DjangoTemplates instances
    """
    engines = []
    template_settings = settings.TEMPLATES

    for params in template_settings:
        copied_params = deepcopy(params)
        backend = copied_params.pop('BACKEND')

        if backend == 'django.template.backends.django.DjangoTemplates':
            copied_params['NAME'] = 'django'
            engines.append(DjangoTemplates(params=copied_params))
        else:
            output_message(reason=2)

    return engines
예제 #28
0
    def test_templatetag_discovery(self):
        engine = DjangoTemplates({
            'DIRS': [],
            'APP_DIRS': False,
            'NAME': 'django',
            'OPTIONS': {
                'libraries': {
                    'alternate':
                    'template_backends.apps.good.templatetags.good_tags',
                    'override':
                    'template_backends.apps.good.templatetags.good_tags',
                },
            },
        })

        # libraries are discovered from installed applications
        self.assertEqual(
            engine.engine.libraries['good_tags'],
            'template_backends.apps.good.templatetags.good_tags',
        )
        self.assertEqual(
            engine.engine.libraries['subpackage.tags'],
            'template_backends.apps.good.templatetags.subpackage.tags',
        )
        # libraries are discovered from django.templatetags
        self.assertEqual(
            engine.engine.libraries['static'],
            'django.templatetags.static',
        )
        # libraries passed in OPTIONS are registered
        self.assertEqual(
            engine.engine.libraries['alternate'],
            'template_backends.apps.good.templatetags.good_tags',
        )
        # libraries passed in OPTIONS take precedence over discovered ones
        self.assertEqual(
            engine.engine.libraries['override'],
            'template_backends.apps.good.templatetags.good_tags',
        )
예제 #29
0
파일: test_django.py 프로젝트: tbbug/django
    def test_templatetag_discovery(self):
        engine = DjangoTemplates({
            "DIRS": [],
            "APP_DIRS": False,
            "NAME": "django",
            "OPTIONS": {
                "libraries": {
                    "alternate":
                    ("template_backends.apps.good.templatetags.good_tags"),
                    "override":
                    ("template_backends.apps.good.templatetags.good_tags"),
                },
            },
        })

        # libraries are discovered from installed applications
        self.assertEqual(
            engine.engine.libraries["good_tags"],
            "template_backends.apps.good.templatetags.good_tags",
        )
        self.assertEqual(
            engine.engine.libraries["subpackage.tags"],
            "template_backends.apps.good.templatetags.subpackage.tags",
        )
        # libraries are discovered from django.templatetags
        self.assertEqual(
            engine.engine.libraries["static"],
            "django.templatetags.static",
        )
        # libraries passed in OPTIONS are registered
        self.assertEqual(
            engine.engine.libraries["alternate"],
            "template_backends.apps.good.templatetags.good_tags",
        )
        # libraries passed in OPTIONS take precedence over discovered ones
        self.assertEqual(
            engine.engine.libraries["override"],
            "template_backends.apps.good.templatetags.good_tags",
        )
예제 #30
0
파일: views.py 프로젝트: manshufeier/qbsy
    def render(self, request, templ, cxt):
        if cxt == None:
            cxt = {}
        cxt['template_name'] = templ
        cxt['site'] = self.site
        cxt['view'] = self
        cxt['view_name'] = self.__class__.__name__
        cxt['me'] = self.get_me()
        cxt['STATIC_URL'] = '/static/'
        cxt['kw'] = request.GET.get('kw', '')
        cxt['request'] = request
        if self.get_me() and self.request.GET.get('modelname'):
            cxt['mp'] = self.get_model_permission()

        templpath = settings.TEMPLATE_BASE_DIR
        from django.conf import settings as gsettings
        from django.template.backends.django import DjangoTemplates
        if templpath not in self.site.template_engines:
            self.site.template_engines[templpath] = DjangoTemplates({
                'APP_DIRS':
                False,
                'DIRS': [templpath],
                'NAME':
                'django',
                'OPTIONS': {
                    'allowed_include_roots': gsettings.ALLOWED_INCLUDE_ROOTS,
                    'context_processors':
                    gsettings.TEMPLATE_CONTEXT_PROCESSORS,
                    'debug': gsettings.TEMPLATE_DEBUG,
                    'loaders': gsettings.TEMPLATE_LOADERS,
                    'string_if_invalid': gsettings.TEMPLATE_STRING_IF_INVALID,
                }
            })
        ng = self.site.template_engines[templpath]
        content = ng.get_template(templ).render(Context(cxt))
        return HttpResponse(content=content)