我们从Python开源项目中,提取了以下27个代码示例,用于说明如何使用django.template.Engine()。
def directory_index(path, fullpath): try: t = loader.select_template([ 'static/directory_index.html', 'static/directory_index', ]) except TemplateDoesNotExist: t = Engine().from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE) files = [] for f in os.listdir(fullpath): if not f.startswith('.'): if os.path.isdir(os.path.join(fullpath, f)): f += '/' files.append(f) c = Context({ 'directory': path + '/', 'file_list': files, }) return HttpResponse(t.render(c))
def page_not_found(request, template_name='404.html'): context = { 'request_path': request.path, 'error': { 'title': _('Page not found'), 'message': _("We tried but couldn't find this page, sorry."), }, } try: template = loader.get_template(template_name) body = template.render(context, request) content_type = None except TemplateDoesNotExist: template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested URL {{ request_path }} was not found on this server.</p>') body = template.render(Context(context)) content_type = 'text/html' return HttpResponseNotFound(body, content_type=content_type)
def directory_index(path, fullpath): try: t = loader.select_template([ 'static/directory_index.html', 'static/directory_index', ]) except TemplateDoesNotExist: t = Engine(libraries={'i18n': 'django.templatetags.i18n'}).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE) files = [] for f in os.listdir(fullpath): if not f.startswith('.'): if os.path.isdir(os.path.join(fullpath, f)): f += '/' files.append(f) c = Context({ 'directory': path + '/', 'file_list': files, }) return HttpResponse(t.render(c))
def page_not_found(request, template_name='404.html'): """ Default 404 handler. Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') """ context = {'request_path': request.path} try: template = loader.get_template(template_name) body = template.render(context, request) content_type = None # Django will use DEFAULT_CONTENT_TYPE except TemplateDoesNotExist: template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested URL {{ request_path }} was not found on this server.</p>') body = template.render(Context(context)) content_type = 'text/html' return http.HttpResponseNotFound(body, content_type=content_type)
def render_javascript_catalog(catalog=None, plural=None): template = Engine().from_string(js_catalog_template) indent = lambda s: s.replace('\n', '\n ') context = Context({ 'catalog_str': indent(json.dumps( catalog, sort_keys=True, indent=2)) if catalog else None, 'formats_str': indent(json.dumps( get_formats(), sort_keys=True, indent=2)), 'plural': plural, }) return http.HttpResponse(template.render(context), 'text/javascript')
def page_not_found(request, exception, template_name='404.html'): """ Default 404 handler. Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') exception The message from the exception which triggered the 404 (if one was supplied), or the exception class name """ exception_repr = exception.__class__.__name__ # Try to get an "interesting" exception message, if any (and not the ugly # Resolver404 dictionary) try: message = exception.args[0] except (AttributeError, IndexError): pass else: if isinstance(message, six.text_type): exception_repr = message context = { 'request_path': request.path, 'exception': exception_repr, } try: template = loader.get_template(template_name) body = template.render(context, request) content_type = None # Django will use DEFAULT_CONTENT_TYPE except TemplateDoesNotExist: template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested URL {{ request_path }} was not found on this server.</p>') body = template.render(Context(context)) content_type = 'text/html' return http.HttpResponseNotFound(body, content_type=content_type)
def csrf_failure(request, reason=""): """ Default view used when request fails CSRF protection """ from django.middleware.csrf import REASON_NO_REFERER, REASON_NO_CSRF_COOKIE t = Engine().from_string(CSRF_FAILURE_TEMPLATE) c = Context({ 'title': _("Forbidden"), 'main': _("CSRF verification failed. Request aborted."), 'reason': reason, 'no_referer': reason == REASON_NO_REFERER, 'no_referer1': _( "You are seeing this message because this HTTPS site requires a " "'Referer header' to be sent by your Web browser, but none was " "sent. This header is required for security reasons, to ensure " "that your browser is not being hijacked by third parties."), 'no_referer2': _( "If you have configured your browser to disable 'Referer' headers, " "please re-enable them, at least for this site, or for HTTPS " "connections, or for 'same-origin' requests."), 'no_cookie': reason == REASON_NO_CSRF_COOKIE, 'no_cookie1': _( "You are seeing this message because this site requires a CSRF " "cookie when submitting forms. This cookie is required for " "security reasons, to ensure that your browser is not being " "hijacked by third parties."), 'no_cookie2': _( "If you have configured your browser to disable cookies, please " "re-enable them, at least for this site, or for 'same-origin' " "requests."), 'DEBUG': settings.DEBUG, 'docs_version': get_docs_version(), 'more': _("More information is available with DEBUG=True."), }) return HttpResponseForbidden(t.render(c), content_type='text/html')
def render_javascript_catalog(catalog=None, plural=None): template = Engine().from_string(js_catalog_template) def indent(s): return s.replace('\n', '\n ') context = Context({ 'catalog_str': indent(json.dumps( catalog, sort_keys=True, indent=2)) if catalog else None, 'formats_str': indent(json.dumps( get_formats(), sort_keys=True, indent=2)), 'plural': plural, }) return http.HttpResponse(template.render(context), 'text/javascript')
def render_to_response(self, context, **response_kwargs): def indent(s): return s.replace('\n', '\n ') template = Engine().from_string(js_catalog_template) context['catalog_str'] = indent( json.dumps(context['catalog'], sort_keys=True, indent=2) ) if context['catalog'] else None context['formats_str'] = indent(json.dumps(context['formats'], sort_keys=True, indent=2)) return http.HttpResponse(template.render(Context(context)), 'text/javascript')
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): """ Default 404 handler. Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') exception The message from the exception which triggered the 404 (if one was supplied), or the exception class name """ exception_repr = exception.__class__.__name__ # Try to get an "interesting" exception message, if any (and not the ugly # Resolver404 dictionary) try: message = exception.args[0] except (AttributeError, IndexError): pass else: if isinstance(message, six.text_type): exception_repr = message context = { 'request_path': request.path, 'exception': exception_repr, } try: template = loader.get_template(template_name) body = template.render(context, request) content_type = None # Django will use DEFAULT_CONTENT_TYPE except TemplateDoesNotExist: if template_name != ERROR_404_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested URL {{ request_path }} was not found on this server.</p>') body = template.render(Context(context)) content_type = 'text/html' return http.HttpResponseNotFound(body, content_type=content_type)
def render_template(template_name, **context): """ Render static resource using provided context. Returns: django.utils.safestring.SafeText """ template_dirs = [os.path.join(os.path.dirname(__file__), 'static/html')] engine = Engine(dirs=template_dirs, debug=True) html = engine.get_template(template_name) return html_parser.unescape( html.render(Context(context)) )
def get_mocked_html_response(self, template_name, variables={}): """ Returns the 'template_name' with the 'variables' as a resolved string. """ template_engine = Engine(dirs=[os.path.join(self.BASE_DIR, 'responses')]) template = template_engine.get_template(template_name) return template.render(Context(variables))
def csrf_failure(request, reason="", template_name=CSRF_FAILURE_TEMPLATE_NAME): """ Default view used when request fails CSRF protection """ from django.middleware.csrf import REASON_NO_REFERER, REASON_NO_CSRF_COOKIE c = Context({ 'title': _("Forbidden"), 'main': _("CSRF verification failed. Request aborted."), 'reason': reason, 'no_referer': reason == REASON_NO_REFERER, 'no_referer1': _( "You are seeing this message because this HTTPS site requires a " "'Referer header' to be sent by your Web browser, but none was " "sent. This header is required for security reasons, to ensure " "that your browser is not being hijacked by third parties."), 'no_referer2': _( "If you have configured your browser to disable 'Referer' headers, " "please re-enable them, at least for this site, or for HTTPS " "connections, or for 'same-origin' requests."), 'no_cookie': reason == REASON_NO_CSRF_COOKIE, 'no_cookie1': _( "You are seeing this message because this site requires a CSRF " "cookie when submitting forms. This cookie is required for " "security reasons, to ensure that your browser is not being " "hijacked by third parties."), 'no_cookie2': _( "If you have configured your browser to disable cookies, please " "re-enable them, at least for this site, or for 'same-origin' " "requests."), 'DEBUG': settings.DEBUG, 'docs_version': get_docs_version(), 'more': _("More information is available with DEBUG=True."), }) try: t = loader.get_template(template_name) except TemplateDoesNotExist: if template_name == CSRF_FAILURE_TEMPLATE_NAME: # If the default template doesn't exist, use the string template. t = Engine().from_string(CSRF_FAILURE_TEMPLATE) else: # Raise if a developer-specified template doesn't exist. raise return HttpResponseForbidden(t.render(c), content_type='text/html')
def _copy_template( self, source_path, source_dirname, target_path, target_dirname, context, component_name=None ): prefix_length = len(TEMPLATES_PATH) + 1 # Walk through all the file in source path for root, dirs, files in os.walk(source_path): path_rest = root[prefix_length:] # Rename folder relative_dir = path_rest.replace(source_dirname, target_dirname) target_dir = os.path.join(target_path, relative_dir) if not os.path.exists(target_dir): os.mkdir(target_dir) # Copy file for filename in files: if filename.endswith(IGNORED_FILE_EXTENSIONS) or filename.startswith('.'): continue old_filename = new_filename = filename if component_name: new_filename = filename.replace('COMP_NAME', component_name) old_path = os.path.join(root, old_filename) new_path = os.path.join(target_dir, new_filename) # Read template with open(old_path, 'rb') as template_file: content = template_file.read() # Parse template content = content.decode('utf-8') template = Engine().from_string(content) content = template.render(context) content = content.encode('utf-8') # Save file with open(new_path, 'wb') as new_file: new_file.write(content) rel_path = new_path.replace(settings.BASE_DIR, '') print '[Created] {file}'.format(file=rel_path)