我们从Python开源项目中,提取了以下33个代码示例,用于说明如何使用jinja2.select_autoescape()。
def render(message, template_name, context={}): base_dir = os.path.join(os.getcwd(), 'templates') paths = [base_dir] # Include paths on settings # paths.extend(settings.TEMPLATES) env = Environment( loader=FileSystemLoader(paths), autoescape=select_autoescape(['html'])) template = env.get_template(template_name) default_context = { 'user': message.user } default_context.update(context) return template.render(**default_context)
def environment(self): if not self._environment: self._environment = Environment( loader=PyPlanetLoader.get_loader(), autoescape=select_autoescape(['html', 'xml', 'Txt', 'txt', 'ml', 'ms', 'script.txt', 'Script.Txt']), auto_reload=bool(settings.DEBUG), ) return self._environment
def create_index(self): """ Creates an HTML index page to redirect to an MkDocs generated page. """ from jinja2 import Environment, PackageLoader, select_autoescape env = Environment( loader=PackageLoader('wikidoc', 'templates'), autoescape=select_autoescape(['html', 'xml']) ) template = env.get_template('redirect.html') html_code = template.render(target_url=self._index) file_name = os.path.join(self._out_dir, "index.html") if not os.path.exists(file_name): with open(file_name, "w") as index_file: index_file.write(html_code)
def __init__(self, package, path): self.env = Environment( loader=PackageLoader(package, path), autoescape=select_autoescape(['html']) ) self.env.filters['basename'] = lambda s: os.path.basename(s) self.env.filters['media'] = \ lambda url, ts, *a: shortcuts.reverse_media_url(ts, url, *a)
def __init__(self, **kwargs): """Initialize the Jinja2 environment.""" super(Report, self).__init__(**kwargs) self.env = Environment( loader=PackageLoader("memote.suite.reporting", "templates"), autoescape=select_autoescape(["html", "xml"]) )
def select_autoescape(enabled_extensions=('html', 'htm', 'xml'), disabled_extensions=(), default_for_string=True, default=False): """Intelligently sets the initial value of autoescaping based on the filename of the template. This is the recommended way to configure autoescaping if you do not want to write a custom function yourself. If you want to enable it for all templates created from strings or for all templates with `.html` and `.xml` extensions:: from jinja2 import Environment, select_autoescape env = Environment(autoescape=select_autoescape( enabled_extensions=('html', 'xml'), default_for_string=True, )) Example configuration to turn it on at all times except if the template ends with `.txt`:: from jinja2 import Environment, select_autoescape env = Environment(autoescape=select_autoescape( disabled_extensions=('txt',), default_for_string=True, default=True, )) The `enabled_extensions` is an iterable of all the extensions that autoescaping should be enabled for. Likewise `disabled_extensions` is a list of all templates it should be disabled for. If a template is loaded from a string then the default from `default_for_string` is used. If nothing matches then the initial value of autoescaping is set to the value of `default`. For security reasons this function operates case insensitive. .. versionadded:: 2.9 """ enabled_patterns = tuple('.' + x.lstrip('.').lower() for x in enabled_extensions) disabled_patterns = tuple('.' + x.lstrip('.').lower() for x in disabled_extensions) def autoescape(template_name): if template_name is None: return default_for_string template_name = template_name.lower() if template_name.endswith(enabled_patterns): return True if template_name.endswith(disabled_patterns): return False return default return autoescape
def create_app(loop, settings: Settings=None): settings = settings or Settings() setup_logging(settings) app = Application( client_max_size=1024**2*100, middlewares=(stats_middleware, ErrorLoggingMiddleware().middleware) ) aiohttp_jinja2.setup( app, loader=jinja2.FileSystemLoader(str(THIS_DIR / 'templates')), autoescape=jinja2.select_autoescape(['html', 'xml', 'jinja']), ) app.update( settings=settings, sender=settings.sender_cls(settings=settings, loop=loop), es=ElasticSearch(settings=settings, loop=loop), mandrill_webhook_url=f'https://{settings.host_name}/webhook/mandrill/', mandrill=Mandrill(settings=settings, loop=loop), webhook_auth_key=None, morpheus_api=MorpheusUserApi(settings=settings, loop=loop), stats_request_count='request-stats-count', stats_request_list='request-stats-list', ) app.on_startup.append(app_startup) app.on_cleanup.append(app_cleanup) app.router.add_get('/', index, name='index') app.router.add_get('/l{token}{_:/?}', ClickRedirectView.view(), name='click-redirect') app.router.add_post('/send/email/', EmailSendView.view(), name='send-emails') app.router.add_post('/send/sms/', SmsSendView.view(), name='send-smss') app.router.add_get('/validate/sms/', SmsValidateView.view(), name='validate-smss') methods = '/{method:%s}/' % '|'.join(m.value for m in SendMethod) app.router.add_post('/create-subaccount' + methods, CreateSubaccountView.view(), name='create-subaccount') app.router.add_post('/webhook/test/', TestWebhookView.view(), name='webhook-test') app.router.add_head('/webhook/mandrill/', index, name='webhook-mandrill-head') app.router.add_post('/webhook/mandrill/', MandrillWebhookView.view(), name='webhook-mandrill') app.router.add_get('/webhook/messagebird/', MessageBirdWebhookView.view(), name='webhook-messagebird') app.router.add_get('/user' + methods + 'messages.json', UserMessagesJsonView.view(), name='user-messages') app.router.add_get('/user' + methods + 'message/{id}.html', UserMessageDetailView.view(), name='user-message-get') app.router.add_get('/user' + methods + 'messages.html', UserMessageListView.view(), name='user-message-list') app.router.add_get('/user' + methods + 'aggregation.json', UserAggregationView.view(), name='user-aggregation') app.router.add_get('/user' + methods + '{id}/preview/', UserMessagePreviewView.view(), name='user-preview') app.router.add_get('/admin/', AdminAggregatedView.view(), name='admin') app.router.add_get('/admin/list/', AdminListView.view(), name='admin-list') app.router.add_get('/admin/get/{method}/{id}/', AdminGetView.view(), name='admin-get') app.router.add_get('/stats/requests/', RequestStatsView.view(), name='request-stats') app.router.add_get('/stats/messages/', MessageStatsView.view(), name='message-stats') app.router.add_static('/', str(THIS_DIR / 'static')) return app