def do_replace(eval_ctx, s, old, new, count=None): """Return a copy of the value with all occurrences of a substring replaced with a new one. The first argument is the substring that should be replaced, the second is the replacement string. If the optional third argument ``count`` is given, only the first ``count`` occurrences are replaced: .. sourcecode:: jinja {{ "Hello World"|replace("Hello", "Goodbye") }} -> Goodbye World {{ "aaaaargh"|replace("a", "d'oh, ", 2) }} -> d'oh, d'oh, aaargh """ if count is None: count = -1 if not eval_ctx.autoescape: return str(s).replace(str(old), str(new), count) if (hasattr(old, "__html__") or hasattr(new, "__html__") and not hasattr(s, "__html__")): s = escape(s) else: s = soft_str(s) return s.replace(soft_str(old), soft_str(new), count)
def do_prefix(value: str, prefix: str) -> str: """ Adds a prefix to the supplied value. Parameters: value (str): Value to add the prefix to. prefix (str): Prefix to add to the string. Returns: str: The value with the prefix added. """ return soft_str(prefix) + soft_str(value)
def do_format(value, *args, **kwargs): """Apply the given values to a `printf-style`_ format string, like ``string % values``. .. sourcecode:: jinja {{ "%s, %s!"|format(greeting, name) }} Hello, World! In most cases it should be more convenient and efficient to use the ``%`` operator or :meth:`str.format`. .. code-block:: text {{ "%s, %s!" % (greeting, name) }} {{ "{}, {}!".format(greeting, name) }} .. _printf-style: https://docs.python.org/library/stdtypes.html #printf-style-string-formatting """ if args and kwargs: raise FilterArgumentError( "can't handle positional and keyword arguments at the same time" ) return soft_str(value) % (kwargs or args)
def escape(self, value): """Escape given value.""" value = soft_str(value) if self._engine._escape is None: return value return self._engine._escape(value)
def do_title(s): """Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase. """ return "".join([ item[0].upper() + item[1:].lower() for item in _word_beginning_split_re.split(soft_str(s)) if item ])
def sync_do_join( eval_ctx: "EvalContext", value: t.Iterable, d: str = "", attribute: t.Optional[t.Union[str, int]] = None, ) -> str: """Return a string which is the concatenation of the strings in the sequence. The separator between elements is an empty string per default, you can define it with the optional parameter: .. sourcecode:: jinja {{ [1, 2, 3]|join('|') }} -> 1|2|3 {{ [1, 2, 3]|join }} -> 123 It is also possible to join certain attributes of an object: .. sourcecode:: jinja {{ users|join(', ', attribute='username') }} .. versionadded:: 2.6 The `attribute` parameter was added. """ if attribute is not None: value = map(make_attrgetter(eval_ctx.environment, attribute), value) # no automatic escaping? joining is a lot easier then if not eval_ctx.autoescape: return str(d).join(map(str, value)) # if the delimiter doesn't have an html representation we check # if any of the items has. If yes we do a coercion to Markup if not hasattr(d, "__html__"): value = list(value) do_escape = False for idx, item in enumerate(value): if hasattr(item, "__html__"): do_escape = True else: value[idx] = str(item) if do_escape: d = escape(d) else: d = str(d) return d.join(value) # no html involved, to normal joining return soft_str(d).join(map(soft_str, value))
def make_mentions(text: str) -> str: # Start by finding all possible @mentions mentions = re.findall(r"(@\w+)", text, re.I) if not mentions: return text # Go through each mention and make it a clickable link for mention in mentions: html = markupsafe.Markup( f'<a href="https://twitter.com/{mention[1:]}">{mention}</a>') text = text.replace(mention, html) return markupsafe.soft_str(text)
def format_by(arg: str, format: str) -> str: """Format filter alternative to be used with jinja map filter. The rationale behind this filter is that the built-in format filter can't take in the placeholder values via the map filter, as it takes the format as the first argument. Therefore, this filter achieves a similar goal, but with the arguments swapped. :param arg: The values for the placeholders in the format string. :return: The formatted string. """ return soft_str(format) % arg
def make_urls(text: str) -> str: """Convert all text links in a tweet into an HTML link.""" # Start by finding all possible t.co text links links = re.findall(r"(https://t\.co/[a-z0-9]+)", text, re.I) if not links: return text # Go through each url and make it a clickable link for link in links: html = markupsafe.Markup(f'<a href="{link}">{link}</a>') text = text.replace(link, html) return markupsafe.soft_str(text)
def do_hasprop(obj: any, property: str) -> bool: """ Checks if the object has a specific property. Parameters: obj (any): The object to check the properties of. property (str): Name of the property to check the object has. Returns: (bool): Returns True if the object has the specified property, otherwise False. """ return soft_str(property) in obj
def do_hasprop(obj: any, property: str) -> bool: """ Checks if the object has a specific property. """ return soft_str(property) in obj
def make_hashtags(text: str) -> str: # Go through each hashtag and make it a clickable link for ht in get_all_hashtags(text): html = f'<a href="https://twitter.com/hashtag/{ht[1:]}">{ht}</a>' text = re.sub(fr"({ht})\b", html, text) return markupsafe.soft_str(markupsafe.Markup(text))
def do_trim(value, chars=None): """Strip leading and trailing characters, by default whitespace.""" return soft_str(value).strip(chars)
def do_wordcount(s): """Count the words in that string.""" return len(_word_re.findall(soft_str(s)))
def do_capitalize(s): """Capitalize a value. The first character will be uppercase, all others lowercase. """ return soft_str(s).capitalize()
def do_lower(s): """Convert a value to lowercase.""" return soft_str(s).lower()
def do_upper(s): """Convert a value to uppercase.""" return soft_str(s).upper()
def map_format(value, pattern): return soft_str(pattern) % value
def do_trim(value: str, chars: t.Optional[str] = None) -> str: """Strip leading and trailing characters, by default whitespace.""" return soft_str(value).strip(chars)
def do_center(value: str, width: int = 80) -> str: """Centers the value in a field of a given width.""" return soft_str(value).center(width)