Python django.template.render() Examples

The following are 30 code examples of django.template.render(). 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 , or try the search function .
Example #1
Source File: bootstrap.py    From OpenMDM with Apache License 2.0 8 votes vote down vote up
def render(element, markup_classes):
    element_type = element.__class__.__name__.lower()

    if element_type == 'boundfield':
        add_input_classes(element)
        template = get_template("bootstrapform/field.html")
        context = Context({'field': element, 'classes': markup_classes, 'form': element.form})
    else:
        has_management = getattr(element, 'management_form', None)
        if has_management:
            for form in element.forms:
                for field in form.visible_fields():
                    add_input_classes(field)

            template = get_template("bootstrapform/formset.html")
            context = Context({'formset': element, 'classes': markup_classes})
        else:
            for field in element.visible_fields():
                add_input_classes(field)

            template = get_template("bootstrapform/form.html")
            context = Context({'form': element, 'classes': markup_classes})

    return template.render(context) 
Example #2
Source File: bootstrap.py    From OpenMDM with Apache License 2.0 6 votes vote down vote up
def bootstrap_horizontal(element, label_cols='col-sm-2 col-lg-2'):

    markup_classes = {'label': label_cols, 'value': '', 'single_value': ''}

    for cl in label_cols.split(' '):
        splitted_class = cl.split('-')

        try:
            value_nb_cols = int(splitted_class[-1])
        except ValueError:
            value_nb_cols = config.BOOTSTRAP_COLUMN_COUNT

        if value_nb_cols >= config.BOOTSTRAP_COLUMN_COUNT:
            splitted_class[-1] = config.BOOTSTRAP_COLUMN_COUNT
        else:
            offset_class = cl.split('-')
            offset_class[-1] = 'offset-' + str(value_nb_cols)
            splitted_class[-1] = str(config.BOOTSTRAP_COLUMN_COUNT - value_nb_cols)
            markup_classes['single_value'] += ' ' + '-'.join(offset_class)
            markup_classes['single_value'] += ' ' + '-'.join(splitted_class)

        markup_classes['value'] += ' ' + '-'.join(splitted_class)

    return render(element, markup_classes) 
Example #3
Source File: resources.py    From personfinder with Apache License 2.0 6 votes vote down vote up
def get_rendered(name, lang, extra_key=None,
                 get_vars=lambda: {}, cache_seconds=1, bundle_name=None):
    """Gets the rendered content of a Resource from the cache or the datastore.
    If name is 'foo.html', this looks for a Resource named 'foo.html' to serve
    as a plain file, then a Resource named 'foo.html.template' to render as a
    template.  Returns None if nothing suitable is found.  When rendering a
    template, this calls get_vars() to obtain a dictionary of template
    variables.  The cache is keyed on bundle_name, name, lang, and extra_key;
    use extra_key to capture dependencies on template variables)."""
    bundle_name = bundle_name or active_bundle_name
    cache_key = (bundle_name, name, lang, extra_key)
    content = RENDERED_CACHE.get(cache_key)
    if content is None:
        resource = get_localized(name, lang, bundle_name)
        if resource:  # a plain file is available
            return resource.content  # already cached, no need to cache again
        resource = get_localized(name + '.template', lang, bundle_name)
        if resource:  # a template is available
            content = render_in_lang(resource.get_template(), lang, get_vars())
            RENDERED_CACHE.put(cache_key, content, cache_seconds)
    return content 
Example #4
Source File: template.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def render(template_path, template_dict, debug=False):
  """Renders the template at the given path with the given dict of values.

  Example usage:
    render("templates/index.html", {"name": "Bret", "values": [1, 2, 3]})

  Args:
    template_path: path to a Django template
    template_dict: dictionary of values to apply to the template

  Returns:
    The rendered template as a string.
  """
  if os.environ.get('APPENGINE_RUNTIME') == 'python27':
    warnings.warn(_PYTHON27_DEPRECATION, DeprecationWarning, stacklevel=2)
    t = _load_internal_django(template_path, debug)
  else:
    t = _load_user_django(template_path, debug)
  return t.render(Context(template_dict)) 
Example #5
Source File: bootstrap_tags.py    From waliki with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def as_bootstrap_inline(form):
    template = get_template("bootstrap/form.html")
    form = _preprocess_fields(form)

    for field in form.fields:
        name = form.fields[field].widget.__class__.__name__.lower()
        if not name.startswith("radio") and not name.startswith("checkbox"):
            form.fields[field].widget.attrs["placeholder"] = form.fields[field].label
    css_classes = {
        "label": "sr-only",
        "single_container": "",
        "wrap": "",
    }
    context = {
        "form": form,
        "css_classes": css_classes,
    }
    return template.render(contex) 
Example #6
Source File: forms.py    From django-is-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render(self, context):
        template = self.template.resolve(context)
        # Does this quack like a Template?
        if not callable(getattr(template, 'render', None)):
            # If not, we'll try our cache, and get_template()
            template_name = template
            cache = context.render_context.dicts[0].setdefault(self, {})
            template = cache.get(template_name)
            if template is None:
                template = context.template.engine.get_template(template_name)
                cache[template_name] = template
        # Use the base.Template of a backends.django.Template.
        elif hasattr(template, 'template'):
            template = template.template
        values = {
            name: var.resolve(context)
            for name, var in self.extra_context.items()
        }
        with context.push(**values):
            return template.render(context) 
Example #7
Source File: basic.py    From docassemble with MIT License 6 votes vote down vote up
def run(engines, number=2000, verbose=False):
    basepath = os.path.abspath(os.path.dirname(__file__))
    for engine in engines:
        dirname = os.path.join(basepath, engine)
        if verbose:
            print('%s:' % engine.capitalize())
            print('--------------------------------------------------------')
        else:
            sys.stdout.write('%s:' % engine.capitalize())
        t = timeit.Timer(setup='from __main__ import %s; render = %s(r"%s", %s)'
                                       % (engine, engine, dirname, verbose),
                                 stmt='render()')

        time = t.timeit(number=number) / number
        if verbose:
            print('--------------------------------------------------------')
        print('%.2f ms' % (1000 * time))
        if verbose:
            print('--------------------------------------------------------') 
Example #8
Source File: basic.py    From mako with MIT License 6 votes vote down vote up
def run(engines, number=2000, verbose=False):
    basepath = os.path.abspath(os.path.dirname(__file__))
    for engine in engines:
        dirname = os.path.join(basepath, engine)
        if verbose:
            print('%s:' % engine.capitalize())
            print('--------------------------------------------------------')
        else:
            sys.stdout.write('%s:' % engine.capitalize())
        t = timeit.Timer(setup='from __main__ import %s; render = %s(r"%s", %s)'
                                       % (engine, engine, dirname, verbose),
                                 stmt='render()')

        time = t.timeit(number=number) / number
        if verbose:
            print('--------------------------------------------------------')
        print('%.2f ms' % (1000 * time))
        if verbose:
            print('--------------------------------------------------------') 
Example #9
Source File: basic.py    From docassemble with MIT License 5 votes vote down vote up
def jinja2(dirname, verbose=False):
    from jinja2 import Environment, FileSystemLoader
    env = Environment(loader=FileSystemLoader(dirname))
    template = env.get_template('template.html')
    def render():
        return template.render(title=TITLE, user=USER, list_items=U_ITEMS)
    if verbose:
        print(render())
    return render 
Example #10
Source File: invoicing.py    From django-invoicing with GNU General Public License v2.0 5 votes vote down vote up
def as_html(invoice):
    template = loader.get_template('invoicing/formatters/html.html')
    formatter = HTMLFormatter(invoice)
    data = formatter.get_data()

    try:
        return template.render(Context(data))
    except TypeError:
        return template.render(data) 
Example #11
Source File: template.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def _load_user_django(path, debug):
  """Load the given template using the django found in third_party."""
  abspath = os.path.abspath(path)

  if not debug:
    template = template_cache.get(abspath, None)
  else:
    template = None

  if not template:
    directory, file_name = os.path.split(abspath)
    new_settings = {
        'TEMPLATE_DIRS': (directory,),
        'TEMPLATE_DEBUG': debug,
        'DEBUG': debug,
        }
    old_settings = _swap_settings(new_settings)
    try:
      template = django.template.loader.get_template(file_name)
    finally:
      _swap_settings(old_settings)

    if not debug:
      template_cache[abspath] = template

    def wrap_render(context, orig_render=template.render):


      URLNode = django.template.defaulttags.URLNode
      save_urlnode_render = URLNode.render
      old_settings = _swap_settings(new_settings)
      try:
        URLNode.render = _urlnode_render_replacement
        return orig_render(context)
      finally:
        _swap_settings(old_settings)
        URLNode.render = save_urlnode_render

    template.render = wrap_render

  return template 
Example #12
Source File: template.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def _load_internal_django(path, debug):
  """Load the given template using the django found in apphosting._internal."""
  import google.appengine._internal.django.conf
  import google.appengine._internal.django.template.loader
  from google.appengine._internal import django

  abspath = os.path.abspath(path)

  if not debug:
    template = template_cache.get(abspath, None)
  else:
    template = None

  if not template:
    directory, file_name = os.path.split(abspath)
    settings = dict(
        TEMPLATE_LOADERS=(
            'google.appengine._internal.'
            'django.template.loaders.filesystem.load_template_source',
        ),
        TEMPLATE_DIRS=(directory,),
        TEMPLATE_DEBUG=debug,
        DEBUG=debug)

    django.conf.settings.configure(**settings)
    template = django.template.loader.get_template(file_name)

    if not debug:
      template_cache[abspath] = template

    def wrap_render(context, orig_render=template.render):


      django.conf.settings.configure(**settings)
      return orig_render(context)
    template.render = wrap_render

  return template 
Example #13
Source File: rest_framework.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def render(self, context):
        text = self.nodelist.render(context)
        return pygments_highlight(text, self.lang, self.style) 
Example #14
Source File: rest_framework.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def render_form(serializer, template_pack=None):
    style = {'template_pack': template_pack} if template_pack else {}
    renderer = HTMLFormRenderer()
    return renderer.render(serializer.data, None, {'style': style}) 
Example #15
Source File: rest_framework.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def format_value(value):
    if getattr(value, 'is_hyperlink', False):
        name = six.text_type(value.obj)
        return mark_safe('<a href=%s>%s</a>' % (value, escape(name)))
    if value is None or isinstance(value, bool):
        return mark_safe('<code>%s</code>' % {True: 'true', False: 'false', None: 'null'}[value])
    elif isinstance(value, list):
        if any([isinstance(item, (list, dict)) for item in value]):
            template = loader.get_template('rest_framework/admin/list_value.html')
        else:
            template = loader.get_template('rest_framework/admin/simple_list_value.html')
        context = {'value': value}
        return template.render(context)
    elif isinstance(value, dict):
        template = loader.get_template('rest_framework/admin/dict_value.html')
        context = {'value': value}
        return template.render(context)
    elif isinstance(value, six.string_types):
        if (
            (value.startswith('http:') or value.startswith('https:')) and not
            re.search(r'\s', value)
        ):
            return mark_safe('<a href="{value}">{value}</a>'.format(value=escape(value)))
        elif '@' in value and not re.search(r'\s', value):
            return mark_safe('<a href="mailto:{value}">{value}</a>'.format(value=escape(value)))
        elif '\n' in value:
            return mark_safe('<pre>%s</pre>' % escape(value))
    return six.text_type(value) 
Example #16
Source File: basic.py    From docassemble with MIT License 5 votes vote down vote up
def genshi(dirname, verbose=False):
    from genshi.template import TemplateLoader
    loader = TemplateLoader([dirname], auto_reload=False)
    template = loader.load('template.html')
    def render():
        data = dict(title=TITLE, user=USER, items=ITEMS)
        return template.generate(**data).render('xhtml')

    if verbose:
        print(render())
    return render 
Example #17
Source File: basic.py    From docassemble with MIT License 5 votes vote down vote up
def myghty(dirname, verbose=False):
    from myghty import interp
    interpreter = interp.Interpreter(component_root=dirname)
    def render():
        data = dict(title=TITLE, user=USER, items=ITEMS)
        buffer = StringIO()
        interpreter.execute("template.myt", request_args=data, out_buffer=buffer)
        return buffer.getvalue()
    if verbose:
        print(render())
    return render 
Example #18
Source File: basic.py    From docassemble with MIT License 5 votes vote down vote up
def mako(dirname, verbose=False):
    from mako.template import Template
    from mako.lookup import TemplateLookup
    disable_unicode = (sys.version_info < (3,))
    lookup = TemplateLookup(directories=[dirname], filesystem_checks=False, disable_unicode=disable_unicode)
    template = lookup.get_template('template.html')
    def render():
        return template.render(title=TITLE, user=USER, list_items=U_ITEMS)
    if verbose:
        print(template.code + " " + render())
    return render 
Example #19
Source File: test_jinja2.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_chaining_filterspecs(self):
        self.assertHTMLEqual(
            self.render('{{ image(myimage, "width-200|jpegquality-40") }}', {'myimage': self.image}),
            '<img alt="Test image" src="{}" width="200" height="150">'.format(
                self.get_image_filename(self.image, "width-200.jpegquality-40"))) 
Example #20
Source File: basic.py    From docassemble with MIT License 5 votes vote down vote up
def cheetah(dirname, verbose=False):
    from Cheetah.Template import Template
    filename = os.path.join(dirname, 'template.tmpl')
    template = Template(file=filename)
    def render():
        template.__dict__.update({'title': TITLE, 'user': USER,
                                  'list_items': U_ITEMS})
        return template.respond()

    if verbose:
        print(dir(template))
        print(template.generatedModuleCode())
        print(render())
    return render 
Example #21
Source File: basic.py    From docassemble with MIT License 5 votes vote down vote up
def kid(dirname, verbose=False):
    import kid
    kid.path = kid.TemplatePath([dirname])
    template = kid.Template(file='template.kid')
    def render():
        template = kid.Template(file='template.kid',
                                title=TITLE, user=USER, items=ITEMS)
        return template.serialize(output='xhtml')

    if verbose:
        print(render())
    return render 
Example #22
Source File: forms.py    From django-is-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def fieldset_renderer(context, form, fieldset):
    context_dict = {}
    for data in context:
        context_dict.update(data)
    request = context_dict.pop('request', None)
    values = fieldset[1]
    inline_view = values.get('inline_view_inst')
    context_dict.update({
        'class': values.get('class'),
    })

    rendered_inline_view = (
        inline_view.render(context.new(context_dict), fieldset[0]) if inline_view else ''
    )

    rendered_fieldsets = []
    for sub_fieldset in values.get('fieldsets', ()):
        rendered_fieldset = fieldset_renderer(context, form, sub_fieldset)
        if rendered_fieldset:
            rendered_fieldsets.append(rendered_fieldset)

    fields = values.get('fields')

    if fields or rendered_fieldsets or rendered_inline_view:
        template = values.get('template') or settings.DEFAULT_FIELDSET_TEMPLATE
        context_dict.update({
            'fields': fields,
            'form': form,
            'title': fieldset[0],
            'class': values.get('class'),
            'fieldsets': values.get('fieldsets'),
            'rendered_fieldsets': rendered_fieldsets,
            'rendered_inline_view': rendered_inline_view,
        })
        return render_to_string(template, context_dict, request=request)
    else:
        return '' 
Example #23
Source File: jinja_base.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render_jinja_to_string(filename, context, request=None):
    """
    `context` may be either a dictionary or a Django Context instance (incl. RequestContext).
    """
    template = env.get_template(filename)
    if request:
        context = RequestContext(request, context)
    context = to_dict_context(context)
    return template.render(**context) 
Example #24
Source File: resources.py    From personfinder with Apache License 2.0 5 votes vote down vote up
def render_in_lang(template, lang, vars):
    """Renders a template in a given language.  We use this to ensure that
    Django's idea of the current language matches our cache keys."""
    import django.utils.translation
    original_lang = django.utils.translation.get_language()
    try:
        django.utils.translation.activate(lang)
        return template.render(django.template.Context(vars))
    finally:
        django.utils.translation.activate(original_lang) 
Example #25
Source File: basic.py    From mako with MIT License 5 votes vote down vote up
def jinja2(dirname, verbose=False):
    from jinja2 import Environment, FileSystemLoader
    env = Environment(loader=FileSystemLoader(dirname))
    template = env.get_template('template.html')
    def render():
        return template.render(title=TITLE, user=USER, list_items=U_ITEMS)
    if verbose:
        print(render())
    return render 
Example #26
Source File: bootstrap.py    From OpenMDM with Apache License 2.0 5 votes vote down vote up
def bootstrap_inline(element):
    markup_classes = {'label': 'sr-only', 'value': '', 'single_value': ''}
    return render(element, markup_classes) 
Example #27
Source File: artifacts.py    From FIR with GNU General Public License v3.0 5 votes vote down vote up
def display(self, request, correlated=False, json=False):
        context = RequestContext(request)
        template = get_template(self.__class__.template)
        context['artifact_name'] = self.__class__.display_name
        if correlated:
            context['artifact_values'] = self._correlated
        else:
            context['artifact_values'] = self._artifacts

        context['event'] = self._event

        if not json:
            return template.render(context.flatten(), request)
        else:
            return context.flatten() 
Example #28
Source File: bootstrap_tags.py    From waliki with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render_form(form):
    """same than  {{ form|crispy }} if crispy_forms is installed.
    render using a bootstrap3 templating otherwise"""

    if 'crispy_forms' in settings.INSTALLED_APPS:
        from crispy_forms.templatetags.crispy_forms_filters import as_crispy_form
        return as_crispy_form(form)

    template = get_template("bootstrap/form.html")
    form = _preprocess_fields(form)

    return template.render({"form": form}) 
Example #29
Source File: bootstrap_tags.py    From waliki with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def as_bootstrap_horizontal(form, label_classes=""):
    template = get_template("bootstrap/form.html")
    form = _preprocess_fields(form)

    if label_classes == "":
        label_classes = "col-md-2"

    css_classes = {
        "label": label_classes,
        "single_container": "",
        "wrap": "",
    }

    for label_class in label_classes.split(" "):
        split_class, column_count = label_class.rsplit("-", 1)
        column_count = int(column_count)

        if column_count < 12:
            offset_class = "{split_class}-offset-{column_count}".format(
                split_class=split_class,
                column_count=column_count,
            )
            wrap_class = "{split_class}-{column_count}".format(
                split_class=split_class,
                column_count=12 - column_count,
            )
            css_classes["single_container"] += offset_class + " " + wrap_class + " "
            css_classes["wrap"] += wrap_class + " "
    context = {
        "form": form,
        "css_classes": css_classes,
    }
    return template.render(context) 
Example #30
Source File: rangepaginator.py    From django-rangepaginator with MIT License 5 votes vote down vote up
def paginate_links(page, request, with_canonical=False):
    canonical = prev_page_url = next_page_url = None
    current_url = furl(request.get_full_path() if request else '')

    if with_canonical:
        if current_url.args.get('page') == '1':
            del current_url.args['page']
        canonical = current_url.url

    if page.has_previous():
        prev_page_url = _get_url_with_page_num(
            current_url, page.previous_page_number())
        if request:
            prev_page_url = request.build_absolute_uri(prev_page_url)

    if page.has_next():
        next_page_url = _get_url_with_page_num(
            current_url, page.next_page_number())
        if request:
            next_page_url = request.build_absolute_uri(next_page_url)

    context = {
        'page': page,
        'canonical': canonical,
        'base_url': request.build_absolute_uri(request.path),
        'prev_page_url': prev_page_url,
        'next_page_url': next_page_url,
    }
    template = loader.get_template('django_rangepaginator/link_tags.html')
    return template.render(context)