我们从Python开源项目中,提取了以下29个代码示例,用于说明如何使用django.template.render()。
def render(element, markup_classes): element_type = element.__class__.__name__.lower() if element_type == 'boundfield': add_input_classes(element) template = get_template("materializecssform/field.html") context = {'field': element, 'classes': markup_classes} 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("materializecssform/formset.html") context = {'formset': element, 'classes': markup_classes} else: for field in element.visible_fields(): add_input_classes(field) template = get_template("materializecssform/form.html") context = {'form': element, 'classes': markup_classes} return template.render(context)
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)
def render(element, markup_classes): if isinstance(element, BoundField): add_input_classes(element) template = get_template("bootstrap/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("bootstrap/formset.html") context = Context({'formset': element, 'classes': markup_classes}) else: for field in element.visible_fields(): add_input_classes(field) template = get_template("bootstrap/form.html") context = Context({'form': element, 'classes': markup_classes}) return template.render(context)
def render(self, context): if 'request' not in context: raise ImproperlyConfigured(context_processor_error_msg % 'querystring') params = dict(context['request'].GET) for key, value in self.updates.items(): key = key.resolve(context) value = value.resolve(context) if key not in ('', None): params[key] = value for removal in self.removals: params.pop(removal.resolve(context), None) return escape('?' + urlencode(params, doseq=True)) # {% querystring "name"="abc" "age"=15 %}
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))
def crispy_addon(field, append="", prepend=""): """ Renders a form field using bootstrap's prepended or appended text:: {% crispy_addon form.my_field prepend="$" append=".00" %} You can also just prepend or append like so {% crispy_addon form.my_field prepend="$" %} {% crispy_addon form.my_field append=".00" %} """ if (field): context = Context({ 'field': field, 'form_show_errors': True }) template = loader.get_template('%s/layout/prepended_appended_text.html' % TEMPLATE_PACK) context['crispy_prepended_text'] = prepend context['crispy_appended_text'] = append if not prepend and not append: raise TypeError("Expected a prepend and/or append argument") return template.render(context)
def as_crispy_errors(form, template_pack=TEMPLATE_PACK): """ Renders only form errors the same way as django-crispy-forms:: {% load crispy_forms_tags %} {{ form|as_crispy_errors }} or:: {{ form|as_crispy_errors:"bootstrap" }} """ if isinstance(form, BaseFormSet): template = get_template('%s/errors_formset.html' % template_pack) c = Context({'formset': form}) else: template = get_template('%s/errors.html' % template_pack) c = Context({'form': form}) return template.render(c)
def materializecss(element, label_cols={}): if not label_cols: label_cols = 's12' markup_classes = {'label': label_cols, 'value': '', 'single_value': ''} return render(element, markup_classes)
def bootstrap(element): markup_classes = {'label': '', 'value': '', 'single_value': ''} return render(element, markup_classes)
def bootstrap_inline(element): markup_classes = {'label': 'sr-only', 'value': '', 'single_value': ''} return render(element, markup_classes)
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
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
def render(self, context): catch_outputs = [] for catch in self.manager.get_catches(self.hook_name): template = loader.get_template(catch.template) c_ctx = context['_hooks_%s' % self.hook_name][catch._id] output = template.render(c_ctx) catch_outputs.append(output) return ''.join(catch_outputs)
def notify(notification): if not notification.data: return "invalid notification" template_name = notification.data.get('template', None) if not template_name: return unicode(notification.data) try: template = get_template(join('assets', 'notification', template_name)) context = dict(notice=notification, user=notification.recipient, instance=notification.action_object, parent=notification.target, author=notification.actor) return template.render(context) except TemplateDoesNotExist: return "template does not exist: " + template_name
def as_bootstrap(form): template = get_template("bootstrap/form.html") c = Context({"form": form}) return template.render(c)
def as_crispy_form(form, template_pack=TEMPLATE_PACK, label_class="", field_class=""): """ The original and still very useful way to generate a div elegant form/formset:: {% load crispy_forms_tags %} <form class="uniForm" method="post"> {% csrf_token %} {{ myform|crispy }} </form> or, if you want to explicitly set the template pack:: {{ myform|crispy:"bootstrap" }} In ``bootstrap3`` for horizontal forms you can do:: {{ myform|label_class:"col-lg-2",field_class:"col-lg-8" }} """ if isinstance(form, BaseFormSet): template = uni_formset_template(template_pack) c = Context({ 'formset': form, 'form_show_errors': True, 'form_show_labels': True, 'label_class': label_class, 'field_class': field_class, }) else: template = uni_form_template(template_pack) c = Context({ 'form': form, 'form_show_errors': True, 'form_show_labels': True, 'label_class': label_class, 'field_class': field_class, }) return template.render(c)
def render(self, context): c = self.get_render(context) if self.actual_helper is not None and getattr(self.actual_helper, 'template', False): template = get_template(self.actual_helper.template) else: if c['is_formset']: template = whole_uni_formset_template(self.template_pack) else: template = whole_uni_form_template(self.template_pack) return template.render(c) # {% crispy %} tag
def as_bootstrap_question_form(form): template = get_template("form/question_form.html") c = Context({"form": form}) return template.render(c)
def jinja_process (src, filename): global jinja_env template = jinja_env.get_template(filename) return template.render()
def jinja_process_variable_start_string (src, filename): global jinja_env template = jinja_env.get_template(filename) return template.render()
def django_process(src, filename): compiled = process(src, filename=filename, compiler=DjangoCompiler) print(compiled) t = django.template.Template(compiled) ctx = django.template.Context() return t.render(ctx)
def mako_process(src, filename): t = mako.template.Template(src, lookup=dirlookup,preprocessor=pypugjs.ext.mako.preprocessor, default_filters=['decode.utf8']) return t.render()
def render(self, context): table = self.table.resolve(context) if isinstance(table, tables.TableBase): pass elif hasattr(table, 'model'): queryset = table # We've been given a queryset, create a table using its model and # render that. class OnTheFlyTable(tables.Table): class Meta: model = queryset.model table = OnTheFlyTable(queryset) request = context.get('request') if request: RequestConfig(request).configure(table) else: klass = type(table).__name__ raise ValueError('Expected table or queryset, not {}'.format(klass)) if self.template: template = self.template.resolve(context) else: template = table.template if isinstance(template, six.string_types): template = get_template(template) else: # assume some iterable was given template = select_template(template) # Contexts are basically a `MergeDict`, when you `update()`, it # internally just adds a dict to the list to attempt lookups from. This # is why we're able to `pop()` later. context.update({'table': table}) try: # HACK: # TemplateColumn benefits from being able to use the context # that the table is rendered in. The current way this is # achieved is to temporarily attach the context to the table, # which TemplateColumn then looks for and uses. table.context = context return template.render(context.flatten()) finally: del table.context context.pop()
def render(self, context): # Nodes are not threadsafe so we must store and look up our instance # variables in the current rendering context first if self not in context.render_context: context.render_context[self] = ( template.Variable(self.field), self.attrs, template.Variable(self.html5_required) ) field, attrs, html5_required = context.render_context[self] field = field.resolve(context) try: html5_required = html5_required.resolve(context) except template.VariableDoesNotExist: html5_required = False widgets = getattr(field.field.widget, 'widgets', [field.field.widget]) if isinstance(attrs, dict): attrs = [attrs] * len(widgets) for widget, attr in zip(widgets, attrs): class_name = widget.__class__.__name__.lower() class_name = class_converter.get(class_name, class_name) css_class = widget.attrs.get('class', '') if css_class: if css_class.find(class_name) == -1: css_class += " %s" % class_name else: css_class = class_name if ( TEMPLATE_PACK == 'bootstrap3' and not is_checkbox(field) and not is_file(field) ): css_class += ' form-control' widget.attrs['class'] = css_class # HTML5 required attribute if html5_required and field.field.required and 'required' not in widget.attrs: if field.field.widget.__class__.__name__ is not 'RadioSelect': widget.attrs['required'] = 'required' for attribute_name, attribute in attr.items(): attribute_name = template.Variable(attribute_name).resolve(context) if attribute_name in widget.attrs: widget.attrs[attribute_name] += " " + template.Variable(attribute).resolve(context) else: widget.attrs[attribute_name] = template.Variable(attribute).resolve(context) return field
def get_response_dict(self, helper, context, is_formset): """ Returns a dictionary with all the parameters necessary to render the form/formset in a template. :param attrs: Dictionary with the helper's attributes used for rendering the form/formset :param context: `django.template.Context` for the node :param is_formset: Boolean value. If set to True, indicates we are working with a formset. """ if not isinstance(helper, FormHelper): raise TypeError('helper object provided to {% crispy %} tag must be a crispy.helper.FormHelper object.') attrs = helper.get_attributes(template_pack=self.template_pack) form_type = "form" if is_formset: form_type = "formset" # We take form/formset parameters from attrs if they are set, otherwise we use defaults response_dict = { 'template_pack': settings.CRISPY_TEMPLATE_PACK, '%s_action' % form_type: attrs['attrs'].get("action", ''), '%s_method' % form_type: attrs.get("form_method", 'post'), '%s_tag' % form_type: attrs.get("form_tag", True), '%s_class' % form_type: attrs['attrs'].get("class", ''), '%s_id' % form_type: attrs['attrs'].get("id", ""), '%s_style' % form_type: attrs.get("form_style", None), 'form_error_title': attrs.get("form_error_title", None), 'formset_error_title': attrs.get("formset_error_title", None), 'form_show_errors': attrs.get("form_show_errors", True), 'help_text_inline': attrs.get("help_text_inline", False), 'html5_required': attrs.get("html5_required", False), 'form_show_labels': attrs.get("form_show_labels", True), 'disable_csrf': attrs.get("disable_csrf", False), 'inputs': attrs.get('inputs', []), 'is_formset': is_formset, '%s_attrs' % form_type: attrs.get('attrs', ''), 'flat_attrs': attrs.get('flat_attrs', ''), 'error_text_inline': attrs.get('error_text_inline', True), 'label_class': attrs.get('label_class', ''), 'label_size': attrs.get('label_size', 0), 'field_class': attrs.get('field_class', ''), } # Handles custom attributes added to helpers for attribute_name, value in attrs.items(): if attribute_name not in response_dict: response_dict[attribute_name] = value if 'csrf_token' in context: response_dict['csrf_token'] = context['csrf_token'] return response_dict