def navbar_template(title, url, active=False, disabled=False): """ Compose an HTML anchor <a href='' /> inside a list item <li>. List item can be added one or more class attributes: * active: to highlight currently visited tab * disabled: to disable access, for example for users without specific permissions. """ screen_reader = '' classes = [] if disabled: classes.append('disabled') if active: classes.append('active') screen_reader = '<span class="sr-only">(active)</span>' if classes: classes = ' '.join(classes) template = ('<li class="{classes}"><a href="{url}">{title} ' '{screen_reader}</a></li>') return template.format(classes=classes, url=url, title=title, screen_reader=screen_reader) else: template = ('<li><a href="{url}">{title}</a></li>') return template.format(url=url, title=title)
def color_status(value): template = '<span style="color:{};">{}</span>' if value == OPEN: value = template.format('green', value) elif value == CLOSED: value = template.format('red', value) elif value == 'feedback': value = template.format('orange', value) return mark_safe(value or '')
def load(template, file_extension): widgets = dashing_settings.INSTALLED_WIDGETS output = '' for name in widgets: local_path = 'dashing/{}/{}/{}.{}'.format('widgets', name, name, file_extension) if find(local_path): output += template.format(static(local_path), name) else: path = remote_path(name) if path: path += '{}.{}'.format(name, file_extension) output += template.format(path, name) return mark_safe(output)
def mail_is_usable_to_icon(mailthing): """ Render an icon with tooltip, given account state. """ # {% if mailaccount.is_usable %} # {% mailfeed_rules_count mailaccount %}</td> # <td class="right">{{ mailaccount.mailboxes|length }}</td> # {% else %} # <td></td> # <td></td> # {% endif %} if isinstance(mailthing, models.MailAccount): attr_name = 'is_usable' err_attr = 'conn_error' message_ok = _(u'Account successfully working, tested {ago} ago.') message_er = _(u'Account not working, tested {ago} ago. ' u'Error reported: {err}') else: attr_name = 'is_valid' err_attr = 'check_error' message_ok = _(u'Rule validated successfully and will be ' u'used for next fetch.') message_er = _(u'Rule did not validate. Error reported: {err}') template = (u'<span class="label label-{0}" title="{2}" ' u'data-toggle="tooltip" data-placement="top">' u'<i class="icon icon-fixed-width icon-{1}"></i></span>') if getattr(mailthing, attr_name): return template.format( 'success', 'ok', message_ok.format( ago=onef_naturaldelta(now() - mailthing.date_last_conn) if hasattr(mailthing, 'data_last_conn') else None)) else: error_text = getattr(mailthing, err_attr) if error_text: return template.format( 'danger', 'exclamation', message_er.format( ago=onef_naturaldelta(now() - mailthing.date_last_conn), err=error_text)) else: return template.format( 'warning', 'question', _(u'Account connectivity not yet tested. ' u'Please wait a few seconds and reload ' u'the current page.'))
def mail_is_usable_to_icon(mailthing): """ Render an icon with tooltip, given account state. """ # {% if mailaccount.is_usable %} # {% mailfeed_rules_count mailaccount %}</td> # <td class="right">{{ mailaccount.mailboxes|length }}</td> # {% else %} # <td></td> # <td></td> # {% endif %} if isinstance(mailthing, models.MailAccount): attr_name = 'is_usable' err_attr = 'conn_error' message_ok = _(u'Account successfully working, tested {ago} ago.') message_er = _(u'Account not working, tested {ago} ago. ' u'Error reported: {err}') else: attr_name = 'is_valid' err_attr = 'check_error' message_ok = _(u'Rule validated successfully and will be ' u'used for next fetch.') message_er = _(u'Rule did not validate. Error reported: {err}') template = (u'<span class="label label-{0}" title="{2}" ' u'data-toggle="tooltip" data-placement="top">' u'<i class="icon icon-fixed-width icon-{1}"></i></span>') if getattr(mailthing, attr_name): return template.format('success', 'ok', message_ok.format( ago=onef_naturaldelta(now() - mailthing.date_last_conn) if hasattr(mailthing, 'data_last_conn') else None)) else: error_text = getattr(mailthing, err_attr) if error_text: return template.format( 'danger', 'exclamation', message_er.format( ago=onef_naturaldelta(now() - mailthing.date_last_conn), err=error_text)) else: return template.format('warning', 'question', _(u'Account connectivity not yet tested. ' u'Please wait a few seconds and reload ' u'the current page.'))
def menuitem(context, url, title): request = context['request'] class_attr = '' if request.path == url: class_attr = ' class="active"' template = u'<li{class_attr}><a href="{url}">{title}</a></li>' return mark_safe(template.format(url=esc(url), title=esc(title), class_attr=class_attr))
def custom_field_sort_icon(field, order): template = '<span class="fa fa-sort-{0}-{1}"></span>' if field['type'] == DecisionItemLookup.STRING: icon = 'alpha' else: icon = 'numeric' return template.format(icon, order)
def group_has_work(value, arg): try: return value.group_has_work(arg) except Exception as e: template = "[ERROR] Template-Tag 'group_has_work' in custom_tags.py: An exception of type {0} occurred. Arguments:\n{1!r}" message = template.format(type(e).__name__, e.args) print (message) return False
def render_jcrop_widget(template, crop_settings): """Return template rendered with crop_settings.""" updated_crop_settings = dict(crop_settings) updated_crop_settings['jcrop'] = json.dumps( updated_crop_settings.get('jcrop', '')).replace('"', "'") return (filters.safe(template.format(**updated_crop_settings)) if updated_crop_settings.get("url", "") else "")
def format_name_html(name): """ Create a link (html string) from just the twitter name. """ if name.startswith('@'): name = name[1:] template = ( '<a href=\'https://twitter.com/{n}\' target=\'_blank\'>@{n}</a>') return template.format(n=name)
def format_link_html(href, text=None): """ Create a link (html string) from just the href. """ if text is None: text = href while '://' in text: text = text[text.index('://') + 3:] template = '<a href=\'{h}\' target=\'_blank\' title=\'{t}\'>{t}</a>' return template.format(h=href, t=text)
def add_page_query(url, page=1, paginator=None, filt=None): """Add page query to the given url.""" template = '{0}?{1}' query = {'page': page} if paginator is not None: query['paginate_by'] = paginator.per_page if filt is not None: query['filter'] = filt return template.format(url, urlencode(query))
def format_name_html(name): """ Create a link (html string) from just the twitter name. """ if name.startswith('@'): name = name[1:] template = ( '<a href=\'https://twitter.com/{n}\' target=\'_blank\'>@{n}</a>' ) return template.format(n=name)
def kolibri_language_globals(context): template = """ <script> var languageCode = '{lang_code}'; var languageDir = '{lang_dir}'; var languages = JSON.parse('{languages}'); var fullCSSFileModern = '{full_css_file_modern}?v={version}'; var fullCSSFileBasic = '{full_css_file_basic}?v={version}'; </script> <link type="text/css" href="{common_css_file}?v={version}" rel="stylesheet"/> <link type="text/css" href="{subset_css_file}?v={version}" rel="stylesheet"/> """ language_code = get_language() lang_dir = "rtl" if get_language_bidi() else "ltr" languages = {} for code, language_name in settings.LANGUAGES: lang_info = next( ( lang for lang in i18n.KOLIBRI_SUPPORTED_LANGUAGES if lang["intl_code"] == code ), None, ) languages[code] = { # Format to match the schema of the content Language model "id": code, "lang_name": language_name, "english_name": lang_info["english_name"] if lang_info else get_language_info(code)["name"], "lang_direction": get_language_info(code)["bidi"], } common_file = static("assets/fonts/noto-common.css") subset_file = static("assets/fonts/noto-subset.{}.css".format(language_code)) full_file = "assets/fonts/noto-full.{}.{}.css" full_file_modern = static(full_file.format(language_code, "modern")) full_file_basic = static(full_file.format(language_code, "basic")) return mark_safe( template.format( lang_code=language_code, lang_dir=lang_dir, languages=json.dumps(languages), common_css_file=common_file, subset_css_file=subset_file, full_css_file_modern=full_file_modern, full_css_file_basic=full_file_basic, # Temporary cache busting strategy. # Would be better to use ManifestStaticFilesStorage version=kolibri.__version__, ) )
def kolibri_theme(): """ A tag to include a theme configuration object to add custom theming to Kolibri. :return: An html string """ template = """ <script> var kolibriTheme = JSON.parse('{theme}'); </script> """ return mark_safe(template.format(theme=json.dumps(ThemeHook().theme)))
def format_hashlink_html(hashtag): """ Create a link (html string) from a hashtag. """ hashlinkfmt = 'https://twitter.com/hashtag/{}?src=hash' template = '<a href=\'{l}\' target=\'_blank\' title=\'{t}\'>{txt}</a>' if hashtag.startswith('#'): hashtag = hashtag[1:] link = hashlinkfmt.format(urlquote(hashtag)) withhash = '#{}'.format(hashtag) return template.format(l=link, t=hashtag, txt=withhash)
def render(self, context): try: module = import_module(self.url_module_name) urls = getattr(module, 'urlpatterns') structure = get_structure_from_urls(RegexURLResolver('^', urls)) template = '<script type="text/javascript">window.{name} = reverser({urls})</script>' return mark_safe(template.format(name=self.as_name, urls=structure)) except AttributeError, e: return u''
def enable_oidc_provider(): """ Specify whether or not the oidc_provider plugin is enabled """ template = """ <script> var oidcProviderEnabled = {}; </script> """ return mark_safe( template.format("true" if OIDCProviderHook().is_enabled else "false") )
def img(*args, **kwargs): """ Receives src, id, class, alt and builds an <img> element. """ image = kwargs.pop('src', None) if not image: image, args = args[0], args[1:] css_id = kwargs.pop('id', '') css_class = kwargs.pop('class', '') alt = kwargs.pop('alt', '') lazy = kwargs.pop('lazy', False) image = image.format(*args, **kwargs).replace('//', '/') src = url(image) try: width, height, bg, _src = img._cache[image] if src != _src: raise KeyError except KeyError: try: path, storage = list(static_finder(image))[0] except IndexError: warnings.warn("Image not found: %s" % image) width, height, bg = '', '', '' else: if storage is not None: _file = storage.open(image) else: _file = image try: _image = Image.open(_file) _image.verify() except Exception: warnings.warn("Invalid image: %s" % image) width, height, bg = '', '', '' else: width, height = _image.size bg = "data:image/png;base64,%s" % b64encode(png(width, height)) img._cache[image] = width, height, bg, src if lazy: template = '<img {css_id} src="{bg}" data-src="{src}" style="opacity:0" {css_class} {width} {height} {alt}>' css_class += ' lazy' else: template = '<img {css_id} src="{src}" {css_class} {width} {height} {alt}>' return template.format( src=src, bg=bg, alt='alt="%s"' % alt if alt else '', css_class='class="%s"' % css_class if css_class else '', css_id='id="%s"' % css_id if css_id else '', width='width="%d"' % width if width else '', height='height="%d"' % height if height else '', )
def render_menu_item(menu_item, level=0): if menu_item.children: if level == 0: template = """ <li class="dropdown dropdown-hover"> <a class="target-offset target-offset dropdown-toggle" href="{}" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" data-submenu="" tabindex="0"> <span class="label-text">{}</span> <span class="label-dropdown-toggle fal fa-angle-down"></span> </a> <a class="dropdown-toggle-mobile" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><span class="dropdown-toggle-mobile-icon fal fa-chevron-square-down fa-2x"></span></a> <ul class="dropdown-menu" role="menu"> {} </ul> </li>""" else: template = """ <li class="dropdown dropdown-hover dropdown-submenu"> <a class="target-offset" href="{}" tabindex="0"> <span class="label-text">{}</span> <span class="label-dropdown-toggle fal fa-angle-right"></span> </a> <a class="dropdown-toggle-mobile" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><span class="dropdown-toggle-mobile-icon fal fa-chevron-square-down fa-2x"></span></a> <ul class="dropdown-menu" role="menu"> {} </ul> </li>""" return mark_safe( template.format( menu_item.url, menu_item.text, "".join([ render_menu_item(item, level + 1) for item in menu_item.children ]))) else: template = """ <li class=""> <a class="target-offset" href="{}" tabindex="0"> <span class="label-text">{}</span> </a> </li>""" return mark_safe(template.format(menu_item.url, menu_item.text))
def _render(name, value, attrs=None): template = ('<label for="{id}" class="btn btn-default control-label">{input} Browse...</label> ' '<span id="{id}_files" class="control-label"></span>' ) onchange = 'document.getElementById("{id}_files").innerText = Array.from(this.files).map(x => x.name)' if not attrs: attrs = {"class": "hidden"} elif not attrs.get("class"): attrs["class"] = "hidden" elif "hidden" not in attrs["class"].split(" "): attrs["class"] += " hidden" attrs["onchange"] = onchange.format(id=attrs['id']) input = widget.__class__.render(widget, name, value, attrs) return template.format(id=attrs['id'], input=input)
def shortname(author): ''' Return author name in format 'Last F.M.' where F is the first name and M is the middle name if present. ''' if author.middle_name: template = u"{last} {first[0]}. {middle[0]}." else: template = u"{last} {first[0]}." return template.format(first=author.first_name, middle=author.middle_name, last=author.last_name)
def kolibri_sentry_error_reporting(): if not conf.OPTIONS["Debug"]["SENTRY_FRONTEND_DSN"]: return "" template = """ <script> var sentryDSN = '{dsn}'; var sentryEnv = '{env}'; </script> """ return mark_safe( template.format( dsn=conf.OPTIONS["Debug"]["SENTRY_FRONTEND_DSN"], env=conf.OPTIONS["Debug"]["SENTRY_ENVIRONMENT"], ))
def documentcloud_embed(slug): """ Returns a DocumentCloud embed ready to serve. """ template = """<div id="DV-viewer-{slug}" class="DV-container"></div> <script src="//s3.amazonaws.com/s3.documentcloud.org/viewer/loader.js"></script> <script> DV.load("//www.documentcloud.org/documents/{slug}.js", {{ container: "#DV-viewer-{slug}", width: 680, height: 850, sidebar: false, zoom: 550, responsive: true }}); </script>""" return mark_safe(template.format(slug=slug))
def __html__(self): css_class = 'btn btn-{btn_class} separated-button'.format(btn_class=self.btn_class) for extra_class in self.btn_extra_classes: css_class += " " + extra_class if self.btn_type == 'a': template = u"<a href='{url}' class='{css_class}'>{name}</a>" elif self.btn_type == 'button': template = u"<button type='submit' class='{css_class}'>{name}</button>" else: raise Exception("Unknown button type: {}".format(self.btn_type)) if self.wrap_btn_group: template = u"""<div class='btn-group'> {} </div>""".format(template) res = template.format(url=self.url, css_class=css_class, name=self.name) return mark_safe(res)
def date_recency(value): if not value: return '' now = datetime.utcnow() delta = relativedelta(now, value) if value >= now - relativedelta(days=1): template = '{delta.hours} hour{hours_suffix} ago' elif value >= now - relativedelta(months=1): template = '{delta.days} day{days_suffix} ago' elif value >= now - relativedelta(years=1): template = '{delta.months} month{months_suffix} ago' else: template = ('{delta.years} year{years_suffix} and ' '{delta.months} month{months_suffix} ago') return template.format( delta=delta, hours_suffix='s' if delta.hours > 1 else '', days_suffix='s' if delta.days > 1 else '', months_suffix='s' if delta.months > 1 else '', years_suffix='s' if delta.years > 1 else '', )
def __html__(self): css_class = 'btn btn-{btn_class} separated-button'.format( btn_class=self.btn_class) for extra_class in self.btn_extra_classes: css_class += " " + extra_class if self.btn_type == 'a': template = u"<a href='{url}' class='{css_class}'>{name}</a>" elif self.btn_type == 'button': template = u"<button type='submit' class='{css_class}'>{name}</button>" else: raise Exception("Unknown button type: {}".format(self.btn_type)) if self.wrap_btn_group: template = u"""<div class='btn-group'> {} </div>""".format( template) res = template.format(url=self.url, css_class=css_class, name=self.name) return mark_safe(res)
def html_mark_safe(template, *args): return mark_safe(template.format(*map(conditional_escape, args)))
def button(url, txt): template = '<div style="padding: 30px;"><a target="_blank" href="{0}" style="{1}" class="button">{2}</a></div>' html = template.format(url, get_styles(), txt) return mark_safe(html)