本文整理汇总了Python中django.template方法的典型用法代码示例。如果您正苦于以下问题:Python django.template方法的具体用法?Python django.template怎么用?Python django.template使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django
的用法示例。
在下文中一共展示了django.template方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import django [as 别名]
# 或者: from django import template [as 别名]
def __init__(self, request, response):
self.initialize(request, response)
api_fixer.ReplaceDefaultArgument(response.set_cookie.im_func, 'secure',
not constants.IS_DEV_APPSERVER)
api_fixer.ReplaceDefaultArgument(response.set_cookie.im_func, 'httponly',
True)
if self.current_user:
self._xsrf_token = xsrf.GenerateToken(_GetXsrfKey(),
self.current_user.email())
if self.app.config.get('using_angular', constants.DEFAULT_ANGULAR):
# AngularJS requires a JS readable XSRF-TOKEN cookie and will pass this
# back in AJAX requests.
self.response.set_cookie('XSRF-TOKEN', self._xsrf_token, httponly=False)
else:
self._xsrf_token = None
self.csp_nonce = _GetCspNonce()
self._RawWrite = self.response.out.write
self.response.out.write = self._ReplacementWrite
# All content should be rendered through a template system to reduce the
# risk/likelihood of XSS issues. Access to the original function
# self.response.out.write is available via self._RawWrite for exceptional
# circumstances.
示例2: render_to_string
# 需要导入模块: import django [as 别名]
# 或者: from django import template [as 别名]
def render_to_string(self, template, template_values=None):
"""Renders template_name with template_values and returns as a string."""
if not template_values:
template_values = {}
template_values['_xsrf'] = self._xsrf_token
template_values['_csp_nonce'] = self.csp_nonce
template_strategy = self.app.config.get('template', constants.CLOSURE)
if template_strategy == constants.DJANGO:
t = django.template.loader.get_template(template)
template_values = django.template.Context(template_values)
return t.render(template_values)
elif template_strategy == constants.JINJA2:
return self.jinja2.render_template(template, **template_values)
else:
ijdata = { 'csp_nonce': self.csp_nonce }
return template(template_values, ijdata)
示例3: Home
# 需要导入模块: import django [as 别名]
# 或者: from django import template [as 别名]
def Home(request):
"""Our Home page.
This also doubles as a general API request handler with a few specific
bits for the home page template."""
# The recent tests table.
recent_tests = memcache.get(key=RECENT_TESTS_MEMCACHE_KEY)
if not recent_tests:
ScheduleRecentTestsUpdate()
show_evolution = False
params = {
'page_title': 'Home',
'message': request.GET.get('message'),
'recent_tests': recent_tests,
'show_evolution': show_evolution,
}
return GetResults(request, template='home.html', params=params,
do_sparse_filter=True)
示例4: GetStatsDataTemplatized
# 需要导入模块: import django [as 别名]
# 或者: from django import template [as 别名]
def GetStatsDataTemplatized(params, template='table'):
"""Returns the stats table run through a template.
Args:
params: Example:
params = {
'v': one of the keys in user_agent.BROWSER_NAV,
'current_user_agent': a user agent entity,
'user_agents': list_of user agents,
'tests': list of test names,
'stats': dict - stats[test_name][user_agent],
'total_runs': total_runs[test_name],
'request_path': request.path,
'params': result_parent.params, #optional
}
"""
params['browser_nav'] = result_stats.BROWSER_NAV
params['is_admin'] = users.is_current_user_admin()
if not re.search('\?', params['request_path']):
params['request_path'] = params['request_path'] + '?'
t = loader.get_template('stats_%s.html' % template)
template_rendered = t.render(Context(params))
return template_rendered
示例5: handle_template
# 需要导入模块: import django [as 别名]
# 或者: from django import template [as 别名]
def handle_template(self, template, subdir):
"""
Determines where the app or project templates are.
Use django.__path__[0] as the default because we don't
know into which directory Django has been installed.
"""
if template is None:
return path.join(django.__path__[0], 'conf', subdir)
else:
if template.startswith('file://'):
template = template[7:]
expanded_template = path.expanduser(template)
expanded_template = path.normpath(expanded_template)
if path.isdir(expanded_template):
return expanded_template
if self.is_url(template):
# downloads the file and returns the path
absolute_path = self.download(template)
else:
absolute_path = path.abspath(expanded_template)
if path.exists(absolute_path):
return self.extract(absolute_path)
raise CommandError("couldn't handle %s template %s." %
(self.app_or_project, template))
示例6: parse
# 需要导入模块: import django [as 别名]
# 或者: from django import template [as 别名]
def parse(cls, parser, token):
"""
Custom parsing for the ``{% ajax_comment_tags for ... %}`` tag.
"""
# Process the template line.
tag_name, args, kwargs = parse_token_kwargs(
parser, token,
allowed_kwargs=cls.allowed_kwargs,
compile_args=False, # Only overrule here, keep at render() phase.
compile_kwargs=cls.compile_kwargs
)
# remove "for" keyword, so all other args can be resolved in render().
if args[0] == 'for':
args.pop(0)
# And apply the compilation afterwards
for i in range(len(args)):
args[i] = parser.compile_filter(args[i])
cls.validate_args(tag_name, *args, **kwargs)
return cls(tag_name, *args, **kwargs)
示例7: get_template_loaders
# 需要导入模块: import django [as 别名]
# 或者: from django import template [as 别名]
def get_template_loaders():
"""
Compatibility method to fetch the template loaders.
Source: https://github.com/django-debug-toolbar/django-debug-toolbar/blob/ece1c2775af108a92a0ef59636266b49e286e916/debug_toolbar/compat.py
"""
try:
from django.template.engine import Engine
except ImportError: # Django < 1.8
Engine = None
if Engine:
try:
engine = Engine.get_default()
except ImproperlyConfigured:
loaders = []
else:
loaders = engine.template_loaders
else: # Django < 1.8
from django.template.loader import find_template_loader
loaders = [
find_template_loader(loader_name)
for loader_name in settings.TEMPLATE_LOADERS]
return loaders
示例8: test_add_to_builtins
# 需要导入模块: import django [as 别名]
# 或者: from django import template [as 别名]
def test_add_to_builtins(self):
from compat import add_to_builtins
# Explicit import of tags
template = Template(
'{% load test_app_tags %}'
'{% my_tag %}'
)
self.assertIn('Return value of my_tag', template.render(Context({})))
# No import
with self.assertRaises(TemplateSyntaxError):
template = Template(
'{% my_tag %}'
)
template.render(Context({}))
# No import but add_to_builtins call
add_to_builtins('compat.tests.test_app.templatetags.test_app_tags')
template = Template(
'{% my_tag %}'
)
self.assertIn('Return value of my_tag', template.render(Context({})))
示例9: load_scenarios_from_path
# 需要导入模块: import django [as 别名]
# 或者: from django import template [as 别名]
def load_scenarios_from_path(self, relative_scenario_dir, include_identifier=False):
"""
Returns an array of (title, xmlcontent) from files contained in a specified directory,
formatted as expected for the return value of the workbench_scenarios() method.
If `include_identifier` is True, returns an array of (identifier, title, xmlcontent).
"""
base_dir = os.path.dirname(os.path.realpath(sys.modules[self.module_name].__file__))
scenario_dir = os.path.join(base_dir, relative_scenario_dir)
scenarios = []
if os.path.isdir(scenario_dir):
for template in sorted(os.listdir(scenario_dir)):
if not template.endswith('.xml'):
continue
identifier = template[:-4]
title = identifier.replace('_', ' ').title()
template_path = os.path.join(relative_scenario_dir, template)
scenario = str(self.render_django_template(template_path, {"url_name": identifier}))
if not include_identifier:
scenarios.append((title, scenario))
else:
scenarios.append((identifier, title, scenario))
return scenarios
示例10: read_template_source
# 需要导入模块: import django [as 别名]
# 或者: from django import template [as 别名]
def read_template_source(filename):
"""Read the source of a Django template, returning the Unicode text."""
# Import this late to be sure we don't trigger settings machinery too
# early.
from django.conf import settings
if not settings.configured:
settings.configure()
with open(filename, "rb") as f:
# The FILE_CHARSET setting will be removed in 3.1:
# https://docs.djangoproject.com/en/3.0/ref/settings/#file-charset
if django.VERSION >= (3, 1):
charset = 'utf-8'
else:
charset = settings.FILE_CHARSET
text = f.read().decode(charset)
return text
示例11: get_line_map
# 需要导入模块: import django [as 别名]
# 或者: from django import template [as 别名]
def get_line_map(self, filename):
"""The line map for `filename`.
A line map is a list of character offsets, indicating where each line
in the text begins. For example, a line map like this::
[13, 19, 30]
means that line 2 starts at character 13, line 3 starts at 19, etc.
Line 1 always starts at character 0.
"""
if filename not in self.source_map:
template_source = read_template_source(filename)
if 0: # change to see the template text
for i in range(0, len(template_source), 10):
print("%3d: %r" % (i, template_source[i:i+10]))
self.source_map[filename] = make_line_map(template_source)
return self.source_map[filename]
示例12: test_get
# 需要导入模块: import django [as 别名]
# 或者: from django import template [as 别名]
def test_get(self):
# Verify that Resource.get fetches a Resource from the datastore.
assert Resource.get('xyz', '1') is None
self.put_resource('1', 'xyz', 10, 'pqr')
assert Resource.get('xyz', '1').content == 'pqr'
self.delete_resource('1', 'xyz')
assert Resource.get('xyz', '1') is None
# Verify that Resource.get fetches a Resource from an existing file.
content = Resource.get('message.html.template', '1').content
assert content != 'pqr'
# Verify that the file can be overriden by a datastore entity.
self.put_resource('1', 'message.html.template', 10, 'pqr')
assert Resource.get('message.html.template', '1').content == 'pqr'
self.delete_resource('1', 'message.html.template')
assert Resource.get('message.html.template', '1').content == content
示例13: render
# 需要导入模块: import django [as 别名]
# 或者: from django import template [as 别名]
def render(self, template, template_values=None):
"""Renders template with template_values and writes to the response."""
template_strategy = self.app.config.get('template', constants.CLOSURE)
self._RawWrite(self.render_to_string(template, template_values))
示例14: Render
# 需要导入模块: import django [as 别名]
# 或者: from django import template [as 别名]
def Render(request, template, params={}):
"""Wrapper function to render templates with global and category vars."""
params['app_title'] = settings.APP_TITLE
params['version_id'] = os.environ['CURRENT_VERSION_ID']
params['build'] = settings.BUILD
params['epoch'] = int(time.time())
params['request_path'] = request.get_full_path()
params['request_path_lastbit'] = re.sub('^.+\/([^\/]+$)', '\\1', request.path)
params['current_ua_string'] = request.META['HTTP_USER_AGENT']
params['current_ua'] = user_agent_parser.PrettyUserAgent(params['current_ua_string'])
params['chromeframe_enabled'] = request.COOKIES.get(
'browserscope-chromeframe-enabled', '0')
params['app_categories'] = []
params['is_admin'] = users.is_current_user_admin()
current_user = users.get_current_user()
if current_user:
params['user_id'] = current_user.user_id()
else:
params['user_id'] = None
params['user'] = current_user
params['sign_in'] = users.create_login_url(request.get_full_path())
params['sign_out'] = users.create_logout_url('/')
return shortcuts.render_to_response(template, params)
示例15: configure
# 需要导入模块: import django [as 别名]
# 或者: from django import template [as 别名]
def configure(config_dict={}, django_admin=False):
_create_app(inspect.stack()) # load application from parent module
if 'BASE_DIR' in config_dict:
config_dict.setdefault('TEMPLATE_DIRS', [os.path.join(config_dict['BASE_DIR'], 'templates')])
if django_admin:
_configure_admin(config_dict)
django_config = {
'INSTALLED_APPS': ['django_micro._app_config'] + config_dict.pop('INSTALLED_APPS', []),
'ROOT_URLCONF': __name__,
'TEMPLATES': [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': config_dict.pop('TEMPLATE_DIRS', []),
'APP_DIRS': True,
'OPTIONS': {
'context_processors': config_dict.pop('CONTEXT_PROCESSORS', []),
'builtins': [__name__],
},
}],
}
django_config.update({key: val for key, val in config_dict.items() if key.isupper()})
settings.configure(**django_config)
django.setup()