本文整理汇总了Python中django.template.base.Template方法的典型用法代码示例。如果您正苦于以下问题:Python base.Template方法的具体用法?Python base.Template怎么用?Python base.Template使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.template.base
的用法示例。
在下文中一共展示了base.Template方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: send_letter_email
# 需要导入模块: from django.template import base [as 别名]
# 或者: from django.template.base import Template [as 别名]
def send_letter_email(request, grad_slug, letter_slug):
letter = get_object_or_404(Letter, slug=letter_slug)
grad = get_object_or_404(GradStudent, person=letter.student.person, slug=grad_slug, program__unit__in=request.units)
if request.method == 'POST':
form = LetterEmailForm(request.POST)
if form.is_valid():
letter.set_email_body(form.cleaned_data['email_body'])
letter.set_email_subject(form.cleaned_data['email_subject'])
if 'email_cc' in form.cleaned_data:
letter.set_email_cc(form.cleaned_data['email_cc'])
letter.set_email_sent(timezone_today())
letter.save()
return _send_letter(request, grad_slug, letter)
else:
email_template = letter.template.email_body()
temp = Template(email_template)
ls = grad.letter_info()
text = temp.render(Context(ls))
form = LetterEmailForm(initial={'email_body': text, 'email_subject': letter.template.email_subject()})
return render(request, 'grad/select_letter_email_text.html', {'form': form, 'grad': grad, 'letter': letter})
示例2: load_template
# 需要导入模块: from django.template import base [as 别名]
# 或者: from django.template.base import Template [as 别名]
def load_template(self, template_name, template_dirs=None):
key = self.cache_key(template_name, template_dirs)
template_tuple = self.template_cache.get(key)
# A cached previous failure:
if template_tuple is TemplateDoesNotExist:
raise TemplateDoesNotExist
elif template_tuple is None:
template, origin = self.find_template(template_name, template_dirs)
if not hasattr(template, 'render'):
try:
template = Template(template, origin, template_name, self.engine)
except TemplateDoesNotExist:
# If compiling the template we found raises TemplateDoesNotExist,
# back off to returning the source and display name for the template
# we were asked to load. This allows for correct identification (later)
# of the actual template that does not exist.
self.template_cache[key] = (template, origin)
self.template_cache[key] = (template, None)
return self.template_cache[key]
示例3: load_template
# 需要导入模块: from django.template import base [as 别名]
# 或者: from django.template.base import Template [as 别名]
def load_template(self, template_name, template_dirs=None):
source, display_name = self.load_template_source(
template_name, template_dirs)
origin = self.engine.make_origin(
display_name, self.load_template_source,
template_name, template_dirs)
try:
template = Template(source, origin, template_name, self.engine)
except TemplateDoesNotExist:
# If compiling the template we found raises TemplateDoesNotExist,
# back off to returning the source and display name for the
# template we were asked to load. This allows for correct
# identification of the actual template that does not exist.
return source, display_name
else:
return template, None
示例4: get_memo_text
# 需要导入模块: from django.template import base [as 别名]
# 或者: from django.template.base import Template [as 别名]
def get_memo_text(request, userid, event_slug, memo_template_id):
""" Get the text from memo template """
person, member_units = _get_faculty_or_404(request.units, userid)
event = _get_event_or_404(units=request.units, slug=event_slug, person=person)
lt = get_object_or_404(MemoTemplate, id=memo_template_id, unit__in=Unit.sub_units(request.units))
temp = Template(lt.template_text)
ls = event.memo_info()
text = temp.render(Context(ls))
return HttpResponse(text, content_type='text/plain')
示例5: get_letter_text
# 需要导入模块: from django.template import base [as 别名]
# 或者: from django.template.base import Template [as 别名]
def get_letter_text(request, grad_slug, letter_template_id):
""" Get the text from letter template """
grad = get_object_or_404(GradStudent, slug=grad_slug, program__unit__in=request.units)
lt = get_object_or_404(LetterTemplate, id=letter_template_id, unit__in=request.units)
temp = Template(lt.content)
ls = grad.letter_info()
text = temp.render(Context(ls))
#print ls
return HttpResponse(text, content_type='text/plain')
示例6: rebuild_template
# 需要导入模块: from django.template import base [as 别名]
# 或者: from django.template.base import Template [as 别名]
def rebuild_template(template_str):
nodes = Template(template_str).compile_nodelist()
expanded = expand_includes(nodes)
tree = lxml.html.fromstring(nodelist_to_template(expanded))
links_to_style(tree)
toronado.inline(tree)
return lxml.html.tostring(tree)
# body = urlopen("http://localhost:4000").read()
# tree = lxml.html.fromstring(body)
示例7: test_render
# 需要导入模块: from django.template import base [as 别名]
# 或者: from django.template.base import Template [as 别名]
def test_render():
"""
Test-drive the apptemplate code base by rendering a template.
"""
c = Context()
t = Template('{% extends "admin:admin/base.html" %}')
t.render(c)
示例8: test_cached
# 需要导入模块: from django.template import base [as 别名]
# 或者: from django.template.base import Template [as 别名]
def test_cached():
"""
Test that the template still works when the cached loader is being used.
"""
c = Context()
t = Template('{% extends "admin:admin/base.html" %}')
t.render(c)
示例9: _evaluate_row_action_in
# 需要导入模块: from django.template import base [as 别名]
# 或者: from django.template.base import Template [as 别名]
def _evaluate_row_action_in(action: models.Action, context: Mapping):
"""Evaluate an action_in in the given context.
Given an action IN object and a row index:
1) Create the form and the context
2) Run the template with the context
3) Return the resulting object (HTML?)
:param action: Action object.
:param context: Dictionary with pairs name/value
:return: String with the HTML content resulting from the evaluation
"""
# Get the active columns attached to the action
tuples = [
column_condition_pair
for column_condition_pair in action.column_condition_pair.all()
if column_condition_pair.column.is_active
]
col_values = [context[colcon_pair.column.name] for colcon_pair in tuples]
form = forms.EnterActionIn(
None,
tuples=tuples,
context=context,
values=col_values)
# Render the form
return Template(
"""<div align="center">
<p class="lead">{{ description_text }}</p>
{% load crispy_forms_tags %}{{ form|crispy }}
</div>""",
).render(Context(
{
'form': form,
'description_text': action.description_text,
},
))
示例10: get_template
# 需要导入模块: from django.template import base [as 别名]
# 或者: from django.template.base import Template [as 别名]
def get_template(template_name):
"""
Returns a compiled Template object for the given template name,
handling template inheritance recursively.
"""
template, origin = find_template(template_name)
if not hasattr(template, 'render'):
# template needs to be compiled
template = get_template_from_string(template, origin, template_name)
return template
示例11: get_template_from_string
# 需要导入模块: from django.template import base [as 别名]
# 或者: from django.template.base import Template [as 别名]
def get_template_from_string(source, origin=None, name=None):
"""
Returns a compiled Template object for the given template code,
handling template inheritance recursively.
"""
return Template(source, origin, name)
示例12: check_debug
# 需要导入模块: from django.template import base [as 别名]
# 或者: from django.template.base import Template [as 别名]
def check_debug():
"""Check that Django's template debugging is enabled.
Django's built-in "template debugging" records information the plugin needs
to do its work. Check that the setting is correct, and raise an exception
if it is not.
Returns True if the debug check was performed, False otherwise
"""
from django.conf import settings
if not settings.configured:
return False
# I _think_ this check is all that's needed and the 3 "hasattr" checks
# below can be removed, but it's not clear how to verify that
from django.apps import apps
if not apps.ready:
return False
# django.template.backends.django gets loaded lazily, so return false
# until they've been loaded
if not hasattr(django.template, "backends"):
return False
if not hasattr(django.template.backends, "django"):
return False
if not hasattr(django.template.backends.django, "DjangoTemplates"):
raise DjangoTemplatePluginException("Can't use non-Django templates.")
for engine in django.template.engines.all():
if not isinstance(engine, django.template.backends.django.DjangoTemplates):
raise DjangoTemplatePluginException(
"Can't use non-Django templates."
)
if not engine.engine.debug:
raise DjangoTemplatePluginException(
"Template debugging must be enabled in settings."
)
return True
示例13: add_service
# 需要导入模块: from django.template import base [as 别名]
# 或者: from django.template.base import Template [as 别名]
def add_service(request, username, id_string):
data = {}
form = RestServiceForm()
xform = get_object_or_404(
XForm, user__username__iexact=username, id_string__exact=id_string)
if request.method == 'POST':
form = RestServiceForm(request.POST)
restservice = None
if form.is_valid():
service_name = form.cleaned_data['service_name']
service_url = form.cleaned_data['service_url']
try:
rs = RestService(service_url=service_url,
name=service_name, xform=xform)
rs.save()
except IntegrityError:
message = _(u"Service already defined.")
status = 'fail'
else:
status = 'success'
message = (_(u"Successfully added service %(name)s.")
% {'name': service_name})
service_tpl = render_to_string("service.html", {
"sv": rs, "username": xform.user.username,
"id_string": xform.id_string})
restservice = service_tpl
else:
status = 'fail'
message = _(u"Please fill in all required fields")
if form.errors:
for field in form:
message += Template(u"{{ field.errors }}")\
.render(Context({'field': field}))
if request.is_ajax():
response = {'status': status, 'message': message}
if restservice:
response["restservice"] = u"%s" % restservice
return HttpResponse(json.dumps(response))
data['status'] = status
data['message'] = message
data['list_services'] = RestService.objects.filter(xform=xform)
data['form'] = form
data['username'] = username
data['id_string'] = id_string
return render(request, "add-service.html", data)
示例14: iterate_with_template_sources
# 需要导入模块: from django.template import base [as 别名]
# 或者: from django.template.base import Template [as 别名]
def iterate_with_template_sources(
frames,
with_locals=True,
library_frame_context_lines=None,
in_app_frame_context_lines=None,
include_paths_re=None,
exclude_paths_re=None,
locals_processor_func=None,
):
template = None
for f in frames:
try:
frame, lineno = f
except ValueError:
# TODO how can we possibly get anything besides a (frame, lineno) tuple here???
logging.getLogger("elasticapm").error("Malformed list of frames. Frames may be missing in Kibana.")
break
f_code = getattr(frame, "f_code", None)
if f_code:
function_name = frame.f_code.co_name
if function_name == "render":
renderer = getattr(frame, "f_locals", {}).get("self")
if renderer and isinstance(renderer, Node):
if getattr(renderer, "token", None) is not None:
if hasattr(renderer, "source"):
# up to Django 1.8
yield {"lineno": renderer.token.lineno, "filename": renderer.source[0].name}
else:
template = {"lineno": renderer.token.lineno}
# Django 1.9 doesn't have the origin on the Node instance,
# so we have to get it a bit further down the stack from the
# Template instance
elif renderer and isinstance(renderer, Template):
if template and getattr(renderer, "origin", None):
template["filename"] = renderer.origin.name
yield template
template = None
yield get_frame_info(
frame,
lineno,
library_frame_context_lines=library_frame_context_lines,
in_app_frame_context_lines=in_app_frame_context_lines,
with_locals=with_locals,
include_paths_re=include_paths_re,
exclude_paths_re=exclude_paths_re,
locals_processor_func=locals_processor_func,
)
示例15: line_number_range
# 需要导入模块: from django.template import base [as 别名]
# 或者: from django.template.base import Template [as 别名]
def line_number_range(self, frame):
assert frame.f_code.co_name == 'render'
if 0:
dump_frame(frame, label="line_number_range")
render_self = frame.f_locals['self']
if isinstance(render_self, (NodeList, Template)):
return -1, -1
position = position_for_node(render_self)
if position is None:
return -1, -1
if SHOW_TRACING:
print("{!r}: {}".format(render_self, position))
s_start, s_end = position
if isinstance(render_self, TextNode):
first_line = render_self.s.splitlines(True)[0]
if first_line.isspace():
s_start += len(first_line)
elif VerbatimNode and isinstance(render_self, VerbatimNode):
# VerbatimNode doesn't track source the same way. s_end only points
# to the end of the {% verbatim %} opening tag, not the entire
# content. Adjust it to cover all of it.
s_end += len(render_self.content)
elif isinstance(render_self, BlockTranslateNode):
# BlockTranslateNode has a list of text and variable tokens.
# Get the end of the contents by looking at the last token,
# and use its endpoint.
last_tokens = render_self.plural or render_self.singular
s_end = position_for_token(last_tokens[-1])[1]
filename = filename_for_frame(frame)
line_map = self.get_line_map(filename)
start = get_line_number(line_map, s_start)
end = get_line_number(line_map, s_end-1)
if start < 0 or end < 0:
start, end = -1, -1
if SHOW_TRACING:
print("line_number_range({}) -> {}".format(
filename, (start, end)
))
return start, end
# --- FileTracer helpers