本文整理匯總了Python中django.template.loader.render_to_string方法的典型用法代碼示例。如果您正苦於以下問題:Python loader.render_to_string方法的具體用法?Python loader.render_to_string怎麽用?Python loader.render_to_string使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.template.loader
的用法示例。
在下文中一共展示了loader.render_to_string方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: show_comments
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import render_to_string [as 別名]
def show_comments(context):
blog_page = context['blog_page']
entry = context['self']
if blog_page.display_comments:
try:
comment_class = import_model(settings.PUPUT_COMMENTS_PROVIDER)(blog_page, entry)
comment_context = comment_class.get_context()
comment_context.update(context.flatten())
return render_to_string(comment_class.template, context=comment_context)
except AttributeError:
raise Exception('To use comments you need to specify '
'PUPUT_COMMENTS_PROVIDER in settings.')
return ""
# Avoid to import endless_pagination in installed_apps and in the templates
示例2: backbone
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import render_to_string [as 別名]
def backbone(request):
instance_name = instance_settings.SHORT_NAME
instance_templates_base = join('instance_templates', instance_name)
footer_template = join(instance_templates_base, 'footer.html')
try:
footer_content = render_to_string(footer_template)
except:
footer_content = ''
context = {
'site_title': instance_settings.SITE_TITLE,
'app_base': instance_settings.APP_BASE,
'footer': footer_content,
'debug': settings.DEBUG
}
return render(request, "backbone.html", context)
#FIXME: move to models
示例3: generate_svg
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import render_to_string [as 別名]
def generate_svg(genome):
treatments = [
{"function": single_color, "weight": 1},
{"function": two_color, "weight": 4},
{"function": stripes, "weight": 6},
]
treatment_context = genome.weighted_choice(treatments)["function"]
field_color = genome.color()
pattern_color = genome.pick_pair(field_color)
context = {
"emoji": genome.emoji(),
"field_color": field_color.css_color,
"pattern_color": pattern_color.css_color,
}
context.update(treatment_context(genome))
return render_to_string("identicon.svg", context)
示例4: create_digest_email
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import render_to_string [as 別名]
def create_digest_email(user, digest_frequency, as_of):
"""Return the digest email message for user based on when they last received a digest message."""
start = user_digest_start(user, digest_frequency, as_of)
context = notification_digest(user, start, as_of)
logger.debug('Digest as of %s: %s', start, context)
if context:
context['timestamp'] = as_of
context['site'] = Site.objects.get_current()
context['digest_frequency'] = digest_frequency.name
subject = render_to_string('boards/email/email_digest_subject.txt', context=context)
# remove superfluous line breaks
subject = " ".join(subject.splitlines()).strip()
text_body = render_to_string('boards/email/email_digest_message.txt', context=context)
html_body = render_to_string('boards/email/email_digest_message.html', context=context)
email = EmailMultiAlternatives(subject=subject, body=text_body, to=[user.email])
email.attach_alternative(html_body, "text/html")
return email
else:
return None
示例5: notify_mobile_survey_start
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import render_to_string [as 別名]
def notify_mobile_survey_start(self, request, mobile_survey):
admin_email = settings.ADMINS[0][1] if settings.ADMINS else ""
email_context = {
"button_text": _("Logon to {app_name}".format(app_name=settings.APP_NAME)),
"link": request.build_absolute_uri(reverse("home")),
"greeting": _(
"Welcome to Arches! You've just been added to a Mobile Survey. \
Please take a moment to review the mobile_survey description and mobile_survey start and end dates."
),
"closing": _(f"If you have any qustions contact the site administrator at {admin_email}."),
}
html_content = render_to_string("email/general_notification.htm", email_context)
text_content = strip_tags(html_content) # this strips the html, so people will have the text as well.
# create the email, and attach the HTML version as well.
for user in self.get_mobile_survey_users(mobile_survey):
msg = EmailMultiAlternatives(
_("You've been invited to an {app_name} Survey!".format(app_name=settings.APP_NAME)),
text_content,
admin_email,
[user.email],
)
msg.attach_alternative(html_content, "text/html")
msg.send()
示例6: render
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import render_to_string [as 別名]
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, extra_context=None, **kwargs):
super(ShowField, self).render(form, form_style, context, template_pack, extra_context, **kwargs)
if extra_context is None:
extra_context = {}
if hasattr(self, 'wrapper_class'):
extra_context['wrapper_class'] = self.wrapper_class
if self.attrs:
if 'detail-class' in self.attrs:
extra_context['input_class'] = self.attrs['detail-class']
elif 'class' in self.attrs:
extra_context['input_class'] = self.attrs['class']
html = ''
for field, result in self.results:
extra_context['result'] = result
if field in form.fields:
if form.fields[field].widget != forms.HiddenInput:
extra_context['field'] = form[field]
html += loader.render_to_string(self.template, extra_context)
else:
extra_context['field'] = field
html += loader.render_to_string(self.template, extra_context)
return html
示例7: block_top_navbar
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import render_to_string [as 別名]
def block_top_navbar(self, context, nodes):
search_models = []
site_name = self.admin_site.name
if self.global_search_models == None:
models = self.admin_site._registry.keys()
else:
models = self.global_search_models
for model in models:
app_label = model._meta.app_label
if self.has_model_perm(model, "view"):
info = (app_label, model._meta.model_name)
if getattr(self.admin_site._registry[model], 'search_fields', None):
try:
search_models.append({
'title': _('Search %s') % capfirst(model._meta.verbose_name_plural),
'url': reverse('xadmin:%s_%s_changelist' % info, current_app=site_name),
'model': model
})
except NoReverseMatch:
pass
return nodes.append(loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'search_models': search_models, 'search_name': SEARCH_VAR}))
示例8: block_top_navmenu
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import render_to_string [as 別名]
def block_top_navmenu(self, context, nodes):
add_models = []
site_name = self.admin_site.name
if self.global_add_models == None:
models = self.admin_site._registry.keys()
else:
models = self.global_add_models
for model in models:
app_label = model._meta.app_label
if self.has_model_perm(model, "add"):
info = (app_label, model._meta.model_name)
try:
add_models.append({
'title': _('Add %s') % capfirst(model._meta.verbose_name),
'url': reverse('xadmin:%s_%s_add' % info, current_app=site_name),
'model': model
})
except NoReverseMatch:
pass
nodes.append(
loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'add_models': add_models}))
示例9: render
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import render_to_string [as 別名]
def render(self, render_type, context):
"""
Renders the template
:param render_type: the content type to render
:param context: context data dictionary
:return: the rendered content
"""
assert render_type in self.render_types, 'Invalid Render Type'
try:
content = render_to_string('herald/{}/{}.{}'.format(
render_type,
self.template_name,
'txt' if render_type == 'text' else render_type
), context)
except TemplateDoesNotExist:
content = None
if settings.DEBUG:
raise
return content
示例10: send_receipts
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import render_to_string [as 別名]
def send_receipts(invoice, email, amount):
name = invoice.client_full_name
id = invoice.id
# Administrator successful payment receipt
admin_receipt_message = render_to_string(
'emails/admin_receipt.txt', {
'email': email,
'name': name,
'amount': amount,
'id': id,
})
admin_receipt = EmailMessage(
name +
" has successfully paid",
admin_receipt_message,
email,
[email])
admin_receipt.content_subtype = 'html'
admin_receipt.send()
示例11: render_to_response
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import render_to_string [as 別名]
def render_to_response(template_name, context=None,
context_instance=_context_instance_undefined,
content_type=None, status=None, dirs=_dirs_undefined,
dictionary=_dictionary_undefined, using=None):
"""
Returns a HttpResponse whose content is filled with the result of calling
django.template.loader.render_to_string() with the passed arguments.
"""
if (context_instance is _context_instance_undefined
and dirs is _dirs_undefined
and dictionary is _dictionary_undefined):
# No deprecated arguments were passed - use the new code path
content = loader.render_to_string(template_name, context, using=using)
else:
# Some deprecated arguments were passed - use the legacy code path
content = loader.render_to_string(
template_name, context, context_instance, dirs, dictionary,
using=using)
return HttpResponse(content, content_type, status)
示例12: send_mail
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import render_to_string [as 別名]
def send_mail(self, subject_template_name, email_template_name,
context, from_email, to_email, html_email_template_name=None):
"""
Sends a django.core.mail.EmailMultiAlternatives to `to_email`.
"""
subject = loader.render_to_string(subject_template_name, context)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
body = loader.render_to_string(email_template_name, context)
email_message = EmailMultiAlternatives(subject, body, from_email, [to_email])
if html_email_template_name is not None:
html_email = loader.render_to_string(html_email_template_name, context)
email_message.attach_alternative(html_email, 'text/html')
email_message.send()
示例13: render
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import render_to_string [as 別名]
def render(self):
"""
Generates the JavaScript necessary for displaying this Google Map.
"""
params = {'calc_zoom': self.calc_zoom,
'center': self.center,
'dom_id': self.dom_id,
'js_module': self.js_module,
'kml_urls': self.kml_urls,
'zoom': self.zoom,
'polygons': self.polygons,
'polylines': self.polylines,
'icons': self.icons,
'markers': self.markers,
}
params.update(self.extra_context)
return render_to_string(self.template, params)
示例14: form_valid
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import render_to_string [as 別名]
def form_valid(self, form):
"""仮登録と本登録用メールの発行."""
# 仮登録と本登録の切り替えは、is_active屬性を使うと簡単です。
# 退會処理も、is_activeをFalseにするだけにしておくと捗ります。
user = form.save(commit=False)
user.is_active = False
user.save()
# アクティベーションURLの送付
current_site = get_current_site(self.request)
domain = current_site.domain
context = {
'protocol': 'https' if self.request.is_secure() else 'http',
'domain': domain,
'token': dumps(user.pk),
'user': user,
}
subject = render_to_string('register/mail_template/create/subject.txt', context)
message = render_to_string('register/mail_template/create/message.txt', context)
user.email_user(subject, message)
return redirect('register:user_create_done')
示例15: edit_subscription
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import render_to_string [as 別名]
def edit_subscription(request, object_id=None):
instance = None
if object_id is not None:
instance = get_object_or_404(NotificationPreference, pk=object_id, user=request.user)
if request.method == 'POST':
form = NotificationPreferenceForm(instance=instance, data=request.POST, user=request.user)
if form.is_valid():
form.save()
return JsonResponse({'status': 'success'})
else:
errors = render_to_string("fir_notifications/subscribe.html",
{'form': form})
return JsonResponse({'status': 'error', 'data': errors})
else:
form = NotificationPreferenceForm(instance=instance, user=request.user)
return render(request, "fir_notifications/subscribe.html", {'form': form})