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 Project: OpenMDM   Author: OpenMDM   File: bootstrap.py    License: 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 Project: OpenMDM   Author: OpenMDM   File: bootstrap.py    License: 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 Project: waliki   Author: mgaitan   File: bootstrap_tags.py    License: 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 #4
Source Project: mako   Author: sqlalchemy   File: basic.py    License: 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 #5
Source Project: python-compat-runtime   Author: GoogleCloudPlatform   File: template.py    License: 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 #6
Source Project: docassemble   Author: jhpyle   File: basic.py    License: 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 #7
Source Project: django-is-core   Author: matllubos   File: forms.py    License: 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 #8
Source Project: personfinder   Author: google   File: resources.py    License: 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 #9
Source Project: OpenMDM   Author: OpenMDM   File: bootstrap.py    License: Apache License 2.0 5 votes vote down vote up
def bootstrap(element):
    markup_classes = {'label': '', 'value': '', 'single_value': ''}
    return render(element, markup_classes) 
Example #10
Source Project: OpenMDM   Author: OpenMDM   File: bootstrap.py    License: 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 #11
Source Project: FIR   Author: certsocietegenerale   File: artifacts.py    License: 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 #12
Source Project: waliki   Author: mgaitan   File: bootstrap_tags.py    License: 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 #13
Source Project: waliki   Author: mgaitan   File: bootstrap_tags.py    License: 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 #14
Source Project: django-rangepaginator   Author: mvantellingen   File: rangepaginator.py    License: 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) 
Example #15
Source Project: mako   Author: sqlalchemy   File: basic.py    License: 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 #16
Source Project: mako   Author: sqlalchemy   File: basic.py    License: 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 #17
Source Project: mako   Author: sqlalchemy   File: basic.py    License: 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 #18
Source Project: mako   Author: sqlalchemy   File: basic.py    License: 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 #19
Source Project: mako   Author: sqlalchemy   File: basic.py    License: 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 #20
Source Project: mako   Author: sqlalchemy   File: basic.py    License: 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 #21
Source Project: wagtail   Author: wagtail   File: test_jinja2.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render(self, string, context=None, request_context=True):
        if context is None:
            context = {}

        # Add a request to the template, to simulate a RequestContext
        if request_context:
            site = Site.objects.get(is_default_site=True)
            request = self.client.get('/test/', HTTP_HOST=site.hostname)
            context['request'] = request

        template = self.engine.from_string(string)
        return template.render(context) 
Example #22
Source Project: wagtail   Author: wagtail   File: test_jinja2.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_image(self):
        self.assertHTMLEqual(
            self.render('{{ image(myimage, "width-200") }}', {'myimage': self.image}),
            '<img alt="Test image" src="{}" width="200" height="150">'.format(
                self.get_image_filename(self.image, "width-200"))) 
Example #23
Source Project: wagtail   Author: wagtail   File: test_jinja2.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_image_attributes(self):
        self.assertHTMLEqual(
            self.render('{{ image(myimage, "width-200", alt="alternate", class="test") }}', {'myimage': self.image}),
            '<img alt="alternate" src="{}" width="200" height="150" class="test">'.format(
                self.get_image_filename(self.image, "width-200"))) 
Example #24
Source Project: wagtail   Author: wagtail   File: test_jinja2.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_image_assignment(self):
        template = ('{% set background=image(myimage, "width-200") %}'
                    'width: {{ background.width }}, url: {{ background.url }}')
        output = ('width: 200, url: ' + self.get_image_filename(self.image, "width-200"))
        self.assertHTMLEqual(self.render(template, {'myimage': self.image}), output) 
Example #25
Source Project: wagtail   Author: wagtail   File: test_jinja2.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_missing_image(self):
        self.assertHTMLEqual(
            self.render('{{ image(myimage, "width-200") }}', {'myimage': self.bad_image}),
            '<img alt="missing image" src="/media/not-found" width="0" height="0">'
        ) 
Example #26
Source Project: wagtail   Author: wagtail   File: test_jinja2.py    License: 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 #27
Source Project: wagtail   Author: wagtail   File: test_jinja2.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_image_url(self):
        self.assertRegex(
            self.render('{{ image_url(myimage, "width-200") }}', {'myimage': self.image}),
            '/images/.*/width-200/{}'.format(self.image.file.name.split('/')[-1]),
        ) 
Example #28
Source Project: wagtail   Author: wagtail   File: test_jinja2.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_image_url_custom_view(self):
        self.assertRegex(
            self.render('{{ image_url(myimage, "width-200", "wagtailimages_serve_custom_view") }}', {'myimage': self.image}),
            '/testimages/custom_view/.*/width-200/{}'.format(self.image.file.name.split('/')[-1]),
        ) 
Example #29
Source Project: django-invoicing   Author: PragmaticMates   File: invoicing.py    License: 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 #30
Source Project: python-compat-runtime   Author: GoogleCloudPlatform   File: template.py    License: 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