Python django.template.loader.select_template() Examples

The following are 30 code examples of django.template.loader.select_template(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.template.loader , or try the search function .
Example #1
Source File: base.py    From ImitationTmall_Django with GNU General Public License v3.0 6 votes vote down vote up
def inclusion_tag(file_name, context_class=Context, takes_context=False):
    def wrap(func):
        @functools.wraps(func)
        def method(self, context, nodes, *arg, **kwargs):
            _dict = func(self, context, nodes, *arg, **kwargs)
            from django.template.loader import get_template, select_template
            if isinstance(file_name, Template):
                t = file_name
            elif not isinstance(file_name, basestring) and is_iterable(file_name):
                t = select_template(file_name)
            else:
                t = get_template(file_name)

            _dict['autoescape'] = context.autoescape
            _dict['use_l10n'] = context.use_l10n
            _dict['use_tz'] = context.use_tz
            _dict['admin_view'] = context['admin_view']

            csrf_token = context.get('csrf_token', None)
            if csrf_token is not None:
                _dict['csrf_token'] = csrf_token
            nodes.append(t.render(_dict))

        return method
    return wrap 
Example #2
Source File: static.py    From python2017 with MIT License 6 votes vote down vote up
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine(libraries={'i18n': 'django.templatetags.i18n'}).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
        c = Context()
    else:
        c = {}
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c.update({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c)) 
Example #3
Source File: views.py    From python2017 with MIT License 6 votes vote down vote up
def render_flatpage(request, f):
    """
    Internal interface to the flat page view.
    """
    # If registration is required for accessing this page, and the user isn't
    # logged in, redirect to the login page.
    if f.registration_required and not request.user.is_authenticated:
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(request.path)
    if f.template_name:
        template = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
    else:
        template = loader.get_template(DEFAULT_TEMPLATE)

    # To avoid having to always use the "|safe" filter in flatpage templates,
    # mark the title and content as already safe (since they are raw HTML
    # content in the first place).
    f.title = mark_safe(f.title)
    f.content = mark_safe(f.content)

    response = HttpResponse(template.render({'flatpage': f}, request))
    return response 
Example #4
Source File: base.py    From adhocracy4 with GNU Affero General Public License v3.0 6 votes vote down vote up
def render(self, template_name, context):
        languages = self.get_languages(context['receiver'])
        template = select_template([
            '{}.{}.email'.format(template_name, lang)
            for lang in languages
        ])

        # Get the actually chosen language from the template name
        language = template.template.name.split('.', 2)[-2]

        with translation.override(language):
            parts = []
            for part_type in ('subject', 'txt', 'html'):
                context['part_type'] = part_type
                parts.append(template.render(context))
                context.pop('part_type')

        return tuple(parts) 
Example #5
Source File: views.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def render_flatpage(request, f):
    """
    Internal interface to the flat page view.
    """
    # If registration is required for accessing this page, and the user isn't
    # logged in, redirect to the login page.
    if f.registration_required and not request.user.is_authenticated():
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(request.path)
    if f.template_name:
        template = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
    else:
        template = loader.get_template(DEFAULT_TEMPLATE)

    # To avoid having to always use the "|safe" filter in flatpage templates,
    # mark the title and content as already safe (since they are raw HTML
    # content in the first place).
    f.title = mark_safe(f.title)
    f.content = mark_safe(f.content)

    response = HttpResponse(template.render({'flatpage': f}, request))
    return response 
Example #6
Source File: static.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine().from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c = Context({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c)) 
Example #7
Source File: views.py    From django-seeker with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _find_field_template(self, field_name):
        """
        finds and sets the default template instance for the given field name with the given template.
        """
        search_templates = []
        if field_name in self.field_templates:
            search_templates.append(self.field_templates[field_name])
        for _cls in inspect.getmro(self.document):
            if issubclass(_cls, dsl.DocType):
                search_templates.append('seeker/%s/%s.html' % (_cls._doc_type.name, field_name))
        search_templates.append('seeker/column.html')
        template = loader.select_template(search_templates)
        existing_templates = list(set(self._field_templates.values()))
        for existing_template in existing_templates:
            #If the template object already exists just re-use the existing one.
            if template.template.name == existing_template.template.name:
                template = existing_template
                break
        self._field_templates.update({field_name: template})
        return template 
Example #8
Source File: base.py    From silver with Apache License 2.0 6 votes vote down vote up
def get_template(self, transaction):
        provider = transaction.document.provider
        provider_slug = slugify(provider.company or provider.name)

        template = select_template([
            'forms/{}/{}_transaction_form.html'.format(
                self.template_slug,
                provider_slug
            ),
            'forms/{}/transaction_form.html'.format(
                self.template_slug
            ),
            'forms/transaction_form.html'
        ])

        return template 
Example #9
Source File: static.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def directory_index(path, fullpath):
    try:
        t = loader.select_template(['static/directory_index.html',
                'static/directory_index'])
    except TemplateDoesNotExist:
        t = Template(DEFAULT_DIRECTORY_INDEX_TEMPLATE, name='Default directory index template')
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c = Context({
        'directory' : path + '/',
        'file_list' : files,
    })
    return HttpResponse(t.render(c)) 
Example #10
Source File: static.py    From python with Apache License 2.0 6 votes vote down vote up
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine(libraries={'i18n': 'django.templatetags.i18n'}).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
        c = Context()
    else:
        c = {}
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c.update({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c)) 
Example #11
Source File: views.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def render_flatpage(request, f):
    """
    Internal interface to the flat page view.
    """
    # If registration is required for accessing this page, and the user isn't
    # logged in, redirect to the login page.
    if f.registration_required and not request.user.is_authenticated:
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(request.path)
    if f.template_name:
        template = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
    else:
        template = loader.get_template(DEFAULT_TEMPLATE)

    # To avoid having to always use the "|safe" filter in flatpage templates,
    # mark the title and content as already safe (since they are raw HTML
    # content in the first place).
    f.title = mark_safe(f.title)
    f.content = mark_safe(f.content)

    response = HttpResponse(template.render({'flatpage': f}, request))
    return response 
Example #12
Source File: static.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine(libraries={'i18n': 'django.templatetags.i18n'}).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
        c = Context()
    else:
        c = {}
    files = []
    for f in fullpath.iterdir():
        if not f.name.startswith('.'):
            url = str(f.relative_to(fullpath))
            if f.is_dir():
                url += '/'
            files.append(url)
    c.update({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c)) 
Example #13
Source File: base.py    From silver with Apache License 2.0 6 votes vote down vote up
def get_template(self, state=None):
        provider_state_template = '{provider}/{kind}_{state}_pdf.html'.format(
            kind=self.kind, provider=self.provider.slug, state=state).lower()
        provider_template = '{provider}/{kind}_pdf.html'.format(
            kind=self.kind, provider=self.provider.slug).lower()
        generic_state_template = '{kind}_{state}_pdf.html'.format(
            kind=self.kind, state=state).lower()
        generic_template = '{kind}_pdf.html'.format(
            kind=self.kind).lower()
        _templates = [provider_state_template, provider_template,
                      generic_state_template, generic_template]

        templates = []
        for t in _templates:
            templates.append('billing_documents/' + t)

        return select_template(templates) 
Example #14
Source File: views.py    From ampcrowd with Apache License 2.0 6 votes vote down vote up
def get_scoped_template(crowd_name, template_name, context=None):
    base_template_name = os.path.join(crowd_name, 'base.html')
    if context is not None:
        try:
            t = get_template(base_template_name)
        except TemplateDoesNotExist:
            base_template_name = 'basecrowd/base.html'
        context['base_template_name'] = base_template_name

    return select_template([
        os.path.join(crowd_name, template_name),
        os.path.join('basecrowd', template_name)])


# When workers submit assignments, we should send data to this view via AJAX
# before submitting to AMT. 
Example #15
Source File: mixins.py    From wagtailmenus with MIT License 6 votes vote down vote up
def get_sub_menu_template(self, level=2):
        if not hasattr(self, '_sub_menu_template_cache'):
            # Initialise cache for this menu instance
            self._sub_menu_template_cache = {}
        elif level in self._sub_menu_template_cache:
            # Return a cached template instance
            return self._sub_menu_template_cache[level]

        template_name = self._get_specified_sub_menu_template_name(level)
        if template_name:
            # A template was specified somehow
            template = get_template(template_name)
        else:
            # A template wasn't specified, so search the filesystem
            template = select_template(
                self.get_sub_menu_template_names(level)
            )

        # Cache the template instance before returning
        self._sub_menu_template_cache[level] = template
        return template 
Example #16
Source File: views.py    From bioforum with MIT License 6 votes vote down vote up
def render_flatpage(request, f):
    """
    Internal interface to the flat page view.
    """
    # If registration is required for accessing this page, and the user isn't
    # logged in, redirect to the login page.
    if f.registration_required and not request.user.is_authenticated:
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(request.path)
    if f.template_name:
        template = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
    else:
        template = loader.get_template(DEFAULT_TEMPLATE)

    # To avoid having to always use the "|safe" filter in flatpage templates,
    # mark the title and content as already safe (since they are raw HTML
    # content in the first place).
    f.title = mark_safe(f.title)
    f.content = mark_safe(f.content)

    response = HttpResponse(template.render({'flatpage': f}, request))
    return response 
Example #17
Source File: static.py    From bioforum with MIT License 6 votes vote down vote up
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine(libraries={'i18n': 'django.templatetags.i18n'}).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
        c = Context()
    else:
        c = {}
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c.update({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c)) 
Example #18
Source File: views.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def render_flatpage(request, f):
    """
    Internal interface to the flat page view.
    """
    # If registration is required for accessing this page, and the user isn't
    # logged in, redirect to the login page.
    if f.registration_required and not request.user.is_authenticated():
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(request.path)
    if f.template_name:
        template = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
    else:
        template = loader.get_template(DEFAULT_TEMPLATE)

    # To avoid having to always use the "|safe" filter in flatpage templates,
    # mark the title and content as already safe (since they are raw HTML
    # content in the first place).
    f.title = mark_safe(f.title)
    f.content = mark_safe(f.content)

    response = HttpResponse(template.render({'flatpage': f}, request))
    return response 
Example #19
Source File: static.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine().from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c = Context({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c)) 
Example #20
Source File: views.py    From django-datatables-view with MIT License 5 votes vote down vote up
def render_row_details(self, id, request=None):

        obj = self.model.objects.get(id=id)

        # Search a custom template for rendering, if available
        try:
            template = loader.select_template([
                'datatables_view/%s/%s/render_row_details.html' % (self.model._meta.app_label, self.model._meta.model_name),
                'datatables_view/%s/render_row_details.html' % (self.model._meta.app_label, ),
                'datatables_view/render_row_details.html',
            ])
            html = template.render({
                'model': self.model,
                'model_admin': self.get_model_admin(),
                'object': obj,
            }, request)

        # Failing that, display a simple table with field values
        except TemplateDoesNotExist:
            fields = [f.name for f in self.model._meta.get_fields() if f.concrete]
            html = '<table class="row-details">'
            for field in fields:
                try:
                    value = getattr(obj, field)
                    html += '<tr><td>%s</td><td>%s</td></tr>' % (field, value)
                except:
                    pass
            html += '</table>'
        return html 
Example #21
Source File: base.py    From online with GNU Affero General Public License v3.0 5 votes vote down vote up
def inclusion_tag(file_name, context_class=Context, takes_context=False):
    def wrap(func):
        @functools.wraps(func)
        def method(self, context, nodes, *arg, **kwargs):
            _dict = func(self, context, nodes, *arg, **kwargs)
            from django.template.loader import get_template, select_template
            cls_str = str if six.PY3 else basestring
            if isinstance(file_name, Template):
                t = file_name
            elif not isinstance(file_name, cls_str) and is_iterable(file_name):
                t = select_template(file_name)
            else:
                t = get_template(file_name)

            _dict['autoescape'] = context.autoescape
            _dict['use_l10n'] = context.use_l10n
            _dict['use_tz'] = context.use_tz
            _dict['admin_view'] = context['admin_view']

            csrf_token = context.get('csrf_token', None)
            if csrf_token is not None:
                _dict['csrf_token'] = csrf_token
            nodes.append(t.render(_dict))

        return method
    return wrap 
Example #22
Source File: base.py    From django-render-block with ISC License 5 votes vote down vote up
def render_block_to_string(template_name, block_name, context=None, request=None):
    """
    Loads the given template_name and renders the given block with the given
    dictionary as context. Returns a string.

        template_name
            The name of the template to load and render. If it's a list of
            template names, Django uses select_template() instead of
            get_template() to find the template.
    """

    # Like render_to_string, template_name can be a string or a list/tuple.
    if isinstance(template_name, (tuple, list)):
        t = loader.select_template(template_name)
    else:
        t = loader.get_template(template_name)

    # Create the context instance.
    context = context or {}

    # The Django backend.
    if isinstance(t, DjangoTemplate):
        return django_render_block(t, block_name, context, request)

    elif isinstance(t, Jinja2Template):
        from render_block.jinja2 import jinja2_render_block
        return jinja2_render_block(t, block_name, context)

    else:
        raise UnsupportedEngine(
            'Can only render blocks from the Django template backend.') 
Example #23
Source File: base.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def inclusion_tag(file_name, context_class=Context, takes_context=False):
    def wrap(func):
        @functools.wraps(func)
        def method(self, context, nodes, *arg, **kwargs):
            _dict = func(self, context, nodes, *arg, **kwargs)
            from django.template.loader import get_template, select_template
            cls_str = str if six.PY3 else basestring
            if isinstance(file_name, Template):
                t = file_name
            elif not isinstance(file_name, cls_str) and is_iterable(file_name):
                t = select_template(file_name)
            else:
                t = get_template(file_name)

            _dict['autoescape'] = context.autoescape
            _dict['use_l10n'] = context.use_l10n
            _dict['use_tz'] = context.use_tz
            _dict['admin_view'] = context['admin_view']

            csrf_token = context.get('csrf_token', None)
            if csrf_token is not None:
                _dict['csrf_token'] = csrf_token
            nodes.append(t.render(_dict))

        return method
    return wrap 
Example #24
Source File: base.py    From devops with MIT License 5 votes vote down vote up
def inclusion_tag(file_name, context_class=Context, takes_context=False):
    def wrap(func):
        @functools.wraps(func)
        def method(self, context, nodes, *arg, **kwargs):
            _dict = func(self, context, nodes, *arg, **kwargs)
            from django.template.loader import get_template, select_template
            if isinstance(file_name, Template):
                t = file_name
            elif not isinstance(file_name, basestring) and is_iterable(file_name):
                t = select_template(file_name)
            else:
                t = get_template(file_name)
            new_context = context_class(_dict, **{
                'autoescape': context.autoescape,
                'current_app': context.current_app,
                'use_l10n': context.use_l10n,
                'use_tz': context.use_tz,
            })
            new_context['admin_view'] = context['admin_view']
            csrf_token = context.get('csrf_token', None)
            if csrf_token is not None:
                new_context['csrf_token'] = csrf_token
            nodes.append(t.render(new_context))

        return method
    return wrap 
Example #25
Source File: renderers.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def resolve_template(self, template_names):
        return loader.select_template(template_names) 
Example #26
Source File: cms_plugins.py    From djangocms-instagram with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_render_template(self, context, instance, placeholder):
        # returns the first template that exists, falling back to bundled template
        return select_template([
            instance.plugin_template,
            settings.DJANGOCMS_INSTAGRAM_DEFAULT_TEMPLATE,
            'djangocms_instagram/default.html'
        ]) 
Example #27
Source File: base.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
def inclusion_tag(file_name, context_class=Context, takes_context=False):
    def wrap(func):
        @functools.wraps(func)
        def method(self, context, nodes, *arg, **kwargs):
            _dict = func(self, context, nodes, *arg, **kwargs)
            from django.template.loader import get_template, select_template
            cls_str = str if six.PY3 else basestring
            if isinstance(file_name, Template):
                t = file_name
            elif not isinstance(file_name, cls_str) and is_iterable(file_name):
                t = select_template(file_name)
            else:
                t = get_template(file_name)

            _dict['autoescape'] = context.autoescape
            _dict['use_l10n'] = context.use_l10n
            _dict['use_tz'] = context.use_tz
            _dict['admin_view'] = context['admin_view']

            csrf_token = context.get('csrf_token', None)
            if csrf_token is not None:
                _dict['csrf_token'] = csrf_token
            nodes.append(t.render(_dict))

        return method
    return wrap 
Example #28
Source File: cms_plugins.py    From djangocms-forms with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_render_template(self, context, instance, placeholder):
        # returns the first template that exists, falling back to bundled template
        return select_template([
            instance.form_template,
            settings.DJANGOCMS_FORMS_DEFAULT_TEMPLATE,
            'djangocms_forms/form_template/default.html'
        ]) 
Example #29
Source File: views.py    From credentials with GNU Affero General Public License v3.0 5 votes vote down vote up
def try_select_theme_template(self, templates):
        """ Select a template or return an empty string if the template doesn't exist.
        Provides ability to check if a template exists before including it.
        """
        try:
            return select_template(self.add_theme_to_template_names(templates))
        except TemplateDoesNotExist:
            return '' 
Example #30
Source File: i18n_assets.py    From credentials with GNU Affero General Public License v3.0 5 votes vote down vote up
def translate_file_path(filepath):
    """
    Uses the filepath parameter to construct a set of potential language suffixed file names, and return
    the template_name of the first template matching the current language, default language if otherwise,
    or if neither the base path requested. Throws a TemplateNotFound exception if none are found.

    The format necessary for filepath should match 'some/path/filename.svg'
    This will search for 'some/path/filename-**.svg' where ** is the requested/default language tags.
    """
    paths = construct_file_language_names(filepath, get_language())
    return select_template(paths).origin.template_name