我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用jinja2.Markup()。
def render_map(): css_js = '' if conf.LOAD_CUSTOM_CSS_FILE: css_js = '<link rel="stylesheet" href="static/css/custom.css">' if conf.LOAD_CUSTOM_JS_FILE: css_js += '<script type="text/javascript" src="static/js/custom.js"></script>' js_vars = Markup( "_defaultSettings['FIXED_OPACITY'] = '{:d}'; " "_defaultSettings['SHOW_TIMER'] = '{:d}'; " "_defaultSettings['TRASH_IDS'] = [{}]; ".format(conf.FIXED_OPACITY, conf.SHOW_TIMER, ', '.join(str(p_id) for p_id in conf.TRASH_IDS))) template = env.get_template('custom.html' if conf.LOAD_CUSTOM_HTML_FILE else 'newmap.html') return html(template.render( area_name=conf.AREA_NAME, map_center=center, map_provider_url=conf.MAP_PROVIDER_URL, map_provider_attribution=conf.MAP_PROVIDER_ATTRIBUTION, social_links=social_links(), init_js_vars=js_vars, extra_css_js=Markup(css_js) ))
def locale_(plugin_id, s): """ Search the plugin that's rendering the template for the requested locale """ if plugin_id == 'prism': ns = prism.settings.PRISM_LOCALE[s] else: plugin = prism.get_plugin(plugin_id) if plugin is None: logging.output('Unknown plugin ID. Offender: %s' % plugin_id) return s ns = plugin.locale[s] if s == ns: return s ns = publish_string(ns, writer=html_fragment_writer).decode('utf-8').rstrip('\r\n') if '<p>' not in ns: return '' ns = ns.split('<p>', 1)[1] ns = ns[:ns.rfind('</p>')] return jinja2.Markup(ns)
def repo_link(repo, show_secret=False): """Convert repo to link to the detail page of that repo :param repo: Repository to show its link :type repo: ``repocribro.models.Repository`` :param show_secret: If secret links should be returned :type show_secret: bool :return: HTML code with link to repository detail page :rtype: ``jinja2.Markup`` """ url = None if repo.is_public: url = flask.url_for('core.repo_detail', login=repo.owner_login, reponame=repo.name) elif repo.is_hidden and show_secret: url = flask.url_for('core.repo_detail_hidden', secret=repo.secret) elif repo.is_private and show_secret: url = flask.url_for('core.repo_detail', login=repo.owner_login, reponame=repo.name) if url is None: return 'Top secret' return jinja2.Markup('<a href="{0}">{0}</a>'.format(url))
def test_repo_link(): repo = Repository(777, None, 'some/project', 'project', 'C++', '', '', False, None, None, Repository.VISIBILITY_PUBLIC) result = repo_link(repo, False) assert 'a href="' in result assert isinstance(result, jinja2.Markup) result = repo_link(repo, True) assert 'a href="' in result assert isinstance(result, jinja2.Markup) repo.visibility_type = Repository.VISIBILITY_HIDDEN repo.generate_secret() result = repo_link(repo, False) assert 'a href="' not in result result = repo_link(repo, True) assert 'a href="' in result assert repo.secret in result assert repo.name not in result assert repo.owner_login not in result assert isinstance(result, jinja2.Markup) repo.visibility_type = Repository.VISIBILITY_PRIVATE result = repo_link(repo, False) assert 'a href="' not in result result = repo_link(repo, True) assert 'a href="' in result assert isinstance(result, jinja2.Markup)
def hidden_tag(self, *fields): """ Wraps hidden fields in a hidden DIV tag, in order to keep XHTML compliance. .. versionadded:: 0.3 :param fields: list of hidden field names. If not provided will render all hidden fields, including the CSRF field. """ if not fields: fields = [f for f in self if _is_hidden(f)] rv = [u'<div style="display:none;">'] for field in fields: if isinstance(field, string_types): field = getattr(self, field) rv.append(text_type(field)) rv.append(u"</div>") return Markup(u"".join(rv))
def include_moment(version = '2.3.1'): if version is not None: if request.is_secure: protocol = 'https' else: protocol = 'http' js = '<script src="%s://cdnjs.cloudflare.com/ajax/libs/moment.js/%s/moment-with-langs.min.js"></script>\n' % (protocol, version) return Markup('''%s<script> function flask_moment_render(elem) { $(elem).text(eval('moment("' + $(elem).data('timestamp') + '").' + $(elem).data('format') + ';')); $(elem).removeClass('flask-moment'); } function flask_moment_render_all() { $('.flask-moment').each(function() { flask_moment_render(this); if ($(this).data('refresh')) { (function(elem, interval) { setInterval(function() { flask_moment_render(elem) }, interval); })(this, $(this).data('refresh')); } }) } $(document).ready(function() { flask_moment_render_all(); }); </script>''' % js)
def include_moment(version='2.5.1', local_js=None): js = '' if local_js is not None: js = '<script src="%s"></script>\n' % local_js elif version is not None: js = '<script src="//cdnjs.cloudflare.com/ajax/libs/' \ 'moment.js/%s/moment-with-langs.min.js"></script>\n' % version return Markup('''%s<script> function flask_moment_render(elem) { $(elem).text(eval('moment("' + $(elem).data('timestamp') + '").' + $(elem).data('format') + ';')); $(elem).removeClass('flask-moment'); } function flask_moment_render_all() { $('.flask-moment').each(function() { flask_moment_render(this); if ($(this).data('refresh')) { (function(elem, interval) { setInterval(function() { flask_moment_render(elem) }, interval); })(this, $(this).data('refresh')); } }) } $(document).ready(function() { flask_moment_render_all(); }); </script>''' % js)
def format_instrumented_list(view, context, model, name): value = getattr(model, name) out = "" if isinstance(value, InstrumentedList): out = "<ul>" for x in value: if x is None: continue if hasattr(x, "admin_view_link"): out += "<li><a href='{}'>{}</a></li>".format( getattr(x, "admin_view_link")(), x) else: out += str(x) out += "</ul>" return Markup(out)
def format_tasks(view, context, model, name): value = getattr(model, name) out = "" if isinstance(value, InstrumentedList): out = "<ul>" for task in value: task_formatted = "<a href={}>{}</a>".format( task.admin_view_link(), task) if task.assignee is not None: task_formatted += " assigned to <a href='{}'>{}</a> ".format( task.assignee.admin_view_link(), str(task.assignee)) else: task_formatted += " not assigned " task_formatted += " (Updated at: {} )".format( task.updated_at.strftime("%Y-%m-%d")) out += "<li>{}</li>".format(task_formatted) out += "</ul>" return Markup(out)
def format_messages(view, context, model, name): value = getattr(model, name) out = "<ul>" if isinstance(value, InstrumentedList): for x in value: if hasattr(x, "admin_view_link"): out += "<li>({authorname}/{messagetitle}/{createdate}) wrote: <br/> {messagecontent}<a href='{messageadminlink}'> Read more...</a></li>".format( authorname=str(x.user), messagetitle=x.title, createdate=str(x.created_at_short), messageadminlink=getattr(x, "admin_view_link")(), messagecontent=x.content) else: out += str(x) out += "</ul>" return Markup(out)
def include_moment(version = '2.3.1'): if version is not None: js = '<script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/%s/moment-with-langs.min.js"></script>\n' % version return Markup('''%s<script> function flask_moment_render(elem) { $(elem).text(eval('moment("' + $(elem).data('timestamp') + '").' + $(elem).data('format') + ';')); $(elem).removeClass('flask-moment'); } function flask_moment_render_all() { $('.flask-moment').each(function() { flask_moment_render(this); if ($(this).data('refresh')) { (function(elem, interval) { setInterval(function() { flask_moment_render(elem) }, interval); })(this, $(this).data('refresh')); } }) } $(document).ready(function() { flask_moment_render_all(); }); </script>''' % js)
def get_assets(asset_type): path = os.path.join(current_app.root_path, current_app.config['TEMPLATE_FOLDER'], 'assets.json') assets = json.load(open(path, 'r')) output = '' if asset_type == 'css': output = '<link rel="stylesheet" href="{0}">'.format(assets['style']['css']) elif asset_type == 'js': manifest = assets['manifest']['js'] manifest = manifest[1:] manifest_file = open(os.path.join(current_app.root_path, current_app.config['STATIC_FOLDER'], manifest), 'r') output += '<script>' + manifest_file.read() + '</script>' manifest_file.close() output += '<script src="{0}"></script>'.format(assets['vendor']['js']) output += '<script src="{0}"></script>'.format(assets['app']['js']) return jinja2.Markup(output)
def wikirender(eval_ctx, wikicode): """ Converts wikicode to the resulting HTML """ r = requests.get('https://en.wikipedia.org/w/api.php', {'action':'parse', 'text':wikicode, 'format':'json', }) result = r.json().get('parse',{}).get('text', {}).get('*','') result = result.replace('href="/wiki/', 'href="https://en.wikipedia.org/wiki/') result = result.replace('<a ','<a target="_blank" ') if eval_ctx.autoescape: result = Markup(result) or wikicode return result or wikicode
def location_schema_html(self): html = [ '<span itemscope itemprop="location" itemtype="http://schema.org/Place">', ' <meta itemprop="name" content="%s" />' % self.actual_city_name, ' <meta itemprop="address" content="%s" />' % self.actual_city_name, ] if self.latitude: html += [ ' <span itemprop="geo" itemscope itemtype="http://schema.org/GeoCoordinates">', ' <meta itemprop="latitude" content="%s" />' % self.latitude, ' <meta itemprop="longitude" content="%s" />' % self.longitude, ' </span>', ] html += [ '</span>', ] return jinja2.Markup('\n'.join(html))
def status_filter(eval_ctx, status): """ Format a status. """ result = None if status: if status.lower() == 'green': result = '<p class="text-success">{}</p>'.format(status) if status.lower() == 'yellow': result = '<p class="text-warning">{}</p>'.format(status) if status.lower() == 'red': result = '<p class="text-danger">{}</p>'.format(status) if result: if eval_ctx.autoescape: return Markup(result) else: return result return status # Task
def test_f_markup(): format_string = 'Hello <b>{0}</b>' format_markup = Markup(format_string) val_string = '<em>Steve</em>' val_markup = Markup(val_string) template = '{{ fmt|f(val) }}' expect = 'Hello <b><em>Steve</em></b>' combinations = ( (format_string, val_string), (format_string, val_markup), (format_markup, val_string), (format_markup, val_markup), ) def _check(f, v): s = render(template, {'fmt': f, 'val': v}) eq_(expect, s) for f, v in combinations: yield _check, f, v
def test_fe_markup(): format_string = 'Hello <b>{0}</b>' format_markup = Markup(format_string) val_string = '<em>Steve</em>' val_markup = Markup(val_string) template = '{{ fmt|fe(val) }}' expect_esc = 'Hello <b><em>Steve</em></b>' expect_noesc = 'Hello <b><em>Steve</em></b>' combinations = ( (format_string, val_string, expect_esc), (format_string, val_markup, expect_noesc), (format_markup, val_string, expect_esc), (format_markup, val_markup, expect_noesc), ) def _check(f, v, e): s = render(template, {'fmt': f, 'val': v}) eq_(e, s) for f, v, e in combinations: yield _check, f, v, e
def tojson_filter(obj, **kwargs): return Markup(htmlsafe_dumps(obj, **kwargs))
def convert_markdown(text): text = textwrap.dedent(text) result = jinja2.Markup(markdown.markdown(text, extensions=['markdown.extensions.fenced_code'])) return result
def hidden_tag(self, *fields): """Render the form's hidden fields in one call. A field is considered hidden if it uses the :class:`~wtforms.widgets.HiddenInput` widget. If ``fields`` are given, only render the given fields that are hidden. If a string is passed, render the field with that name if it exists. .. versionchanged:: 0.13 No longer wraps inputs in hidden div. This is valid HTML 5. .. versionchanged:: 0.13 Skip passed fields that aren't hidden. Skip passed names that don't exist. """ def hidden_fields(fields): for f in fields: if isinstance(f, string_types): f = getattr(self, f, None) if f is None or not isinstance(f.widget, HiddenInput): continue yield f return Markup( u'\n'.join(text_type(f) for f in hidden_fields(fields or self)) )
def render(self, format): return Markup("<script>\ndocument.write(moment(\"%s\").%s);\n</script>" % ( self.timestamp.strftime( "%Y-%m-%dT%H:%M:%S" ), format))
def nl2br(eval_ctx, value): result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n') \ for p in _paragraph_re.split(escape(value))) if eval_ctx.autoescape: result = Markup(result) return result
def do_render(self): return jinja2.Markup(prism.handle_render(self.plugin_id, self.render))
def include_static(name): """ Load a file from the /static/ directory """ desired_file = os.path.join(flask_app.static_folder, name) with open(desired_file) as f: return jinja2.Markup(f.read())
def do_render(self, site_config): return jinja2.Markup(prism.handle_render(self.plugin_id, self.render, site_config))
def newline_br(eval_ctx, value): result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n') \ for p in _paragraph_re.split(escape(value))) if eval_ctx.autoescape: result = Markup(result) return result
def __init__(self, id, name, priority=100, content='', octicon=None, badge=None): self.id = id self.name = name self.content = jinja2.Markup(content) self.priority = priority self.octicon = octicon self.badge = badge
def gh_user_link(user): """Convert user/org to its GitHub URL :param repo: User to show its GitHub URL :type repo: ``repocribro.models.RepositoryOwner`` :return: HTML code with hyperlink to GitHub user/org page :rtype: ``jinja2.Markup`` """ return jinja2.Markup( '<a href="https://github.com/{0}" target="_blank">{0}</a>'.format( user.login ) )
def gh_repo_link(repo): """Convert repo to its GitHub URL :param repo: Repository to show its GitHub URL :type repo: ``repocribro.models.Repository`` :return: HTML code with hyperlink to GitHub repo page :rtype: ``jinja2.Markup`` """ return jinja2.Markup( '<a href="https://github.com/{0}" target="_blank">{0}</a>'.format( repo.full_name ) )
def email_link(email): """Convert email string to HTML link :param email: Email address :type email: str :return: HTML code with hyperlink mailto :rtype: ``jinja2.Markup`` """ if email is None: return '' return jinja2.Markup('<a href="mailto:{0}">{0}</a>'.format(email))
def test_ext_link(): result = ext_link('https://github.com') assert 'https://github.com' in result assert 'href="https://github.com"' in result assert 'target="_blank"' in result assert isinstance(result, jinja2.Markup) assert ext_link(None) == '' # @see http://getbootstrap.com/components/#alerts
def test_gh_user_link(): user = User(111, 'some', '', '', None, '', '', None, None, None, None) result = gh_user_link(user) assert user.login in result assert 'https://github.com' in result assert isinstance(result, jinja2.Markup) org = Organization(111, 'some', '', '', None, '', '', None, None) result = gh_user_link(org) assert org.login in result assert 'https://github.com' in result assert isinstance(result, jinja2.Markup)
def test_gh_repo_link(): repo = Repository(777, None, 'some/repo', 'repo', 'C++', '', '', False, None, None, Repository.VISIBILITY_PRIVATE) result = gh_repo_link(repo) assert repo.full_name in result assert 'https://github.com' in result assert isinstance(result, jinja2.Markup)
def render_markup(text): """Renders the given text as markdown :param text: The text that should be rendered as markdown """ return Markup(markdown.render(text))
def _format_source(self, source): formatter = HtmlFormatter(nowrap=True) html = highlight(source, PythonLexer(), formatter) return { 'html_lines': [Markup(l) for l in html.splitlines()], 'css': formatter.get_style_defs() }
def include_pagedown(self): if request.is_secure: protocol = 'https' else: protocol = 'http' return Markup(''' <script type="text/javascript" src="{0}://cdnjs.cloudflare.com/ajax/libs/pagedown/1.0/Markdown.Converter.min.js"></script> <script type="text/javascript" src="{0}://cdnjs.cloudflare.com/ajax/libs/pagedown/1.0/Markdown.Sanitizer.min.js"></script> '''.format(protocol))