示例#1
0
def do_format(value, *args, **kwargs):
    """
    Apply python string formatting on an object:

    .. sourcecode:: jinja

        {{ "%s - %s"|format("Hello?", "Foo!") }}
            -> Hello? - Foo!
    """
    if args and kwargs:
        raise FilterArgumentError('can\'t handle positional and keyword '
                                  'arguments at the same time')
    try:
        ret = soft_unicode(value) % (kwargs or args)
        if ret != value:
            return ret
    except TypeError:
        pass

    try:
        return soft_unicode(value).format(**kwargs)
    except Exception:
        return soft_unicode(value).format(*args)

    raise FilterArgumentError('Your format filter is badly formed')
示例#2
0
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 text_type(s).replace(text_type(old), text_type(new), count)
    if hasattr(old, '__html__') or hasattr(new, '__html__') and \
       not hasattr(s, '__html__'):
        s = escape(s)
    else:
        s = soft_unicode(s)
    return s.replace(soft_unicode(old), soft_unicode(new), count)
示例#3
0
def do_replace(eval_ctx, s, old, new, count = None):
    if count is None:
        count = -1
    if not eval_ctx.autoescape:
        return unicode(s).replace(unicode(old), unicode(new), count)
    if hasattr(old, '__html__') or hasattr(new, '__html__') and not hasattr(s, '__html__'):
        s = escape(s)
    else:
        s = soft_unicode(s)
    return s.replace(soft_unicode(old), soft_unicode(new), count)
示例#4
0
def figo_format(value, *args, **kwargs):
    """
    Apply python string formatting on an object:

    .. sourcecode:: jinja

        {{ "%s - %s"|format("Hello?", "Foo!") }}
            -> Hello? - Foo!
    """
    if args and kwargs:
        raise FilterArgumentError('can\'t handle positional and keyword arguments at the same time')
    if args:
        return soft_unicode(value.format(*args))
    else:
        return soft_unicode(value.format(**kwargs))
示例#5
0
def do_join(eval_ctx, value, d=u""):
    """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
    """
    # no automatic escaping?  joining is a lot eaiser then
    if not eval_ctx.autoescape:
        return unicode(d).join(imap(unicode, 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] = unicode(item)
        if do_escape:
            d = escape(d)
        else:
            d = unicode(d)
        return d.join(value)

    # no html involved, to normal joining
    return soft_unicode(d).join(imap(soft_unicode, value))
示例#6
0
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_unicode(s))
         if item])
示例#7
0
def map_format(value, pattern):
    """
    Apply python string formatting on an object:
    .. sourcecode:: jinja
        {{ "%s - %s"|format("Hello?", "Foo!") }}
            -> Hello? - Foo!
    """
    return soft_unicode(pattern) % (value)
示例#8
0
    def escape(self, value):
        """Escape given value."""
        value = soft_unicode(value)

        if self._engine._escape is None:  # pylint: disable=protected-access
            return value

        return self._engine._escape(value)  # pylint: disable=protected-access
示例#9
0
def paren_title(s):
    """
    Fix jinja2 title filter to capitalize words inside parens
    see https://github.com/mitsuhiko/jinja2/pull/439
    """
    return ''.join(
        [item[0].upper() + item[1:].lower()
         for item in _word_beginning_split_re.split(soft_unicode(s))
         if item])
示例#10
0
文件: filters.py 项目: 5y/jinja2
def do_title(s):
    """Return a titlecased version of the value. I.e. words will start with
    uppercase letters, all remaining characters are lowercase.
    """
    rv = []
    for item in re.compile(r'([-\s]+)(?u)').split(soft_unicode(s)):
        if not item:
            continue
        rv.append(item[0].upper() + item[1:].lower())
    return ''.join(rv)
示例#11
0
def do_format(value, *args, **kwargs):
    """
    Apply python string formatting on an object:

    .. sourcecode:: jinja

        {{ "%s - %s"|format("Hello?", "Foo!") }}
            -> Hello? - Foo!
    """
    if args and kwargs:
        raise FilterArgumentError("can't handle positional and keyword " "arguments at the same time")
    return soft_unicode(value) % (kwargs or args)
示例#12
0
文件: filters.py 项目: blech/snaptrip
def do_urlize(environment, value, trim_url_limit=None, nofollow=False):
    """Converts URLs in plain text into clickable links.

    If you pass the filter an additional integer it will shorten the urls
    to that number. Also a third argument exists that makes the urls
    "nofollow":

    .. sourcecode:: jinja

        {{ mytext|urlize(40, true) }}
            links are shortened to 40 chars and defined with rel="nofollow"
    """
    rv = urlize(soft_unicode(value), trim_url_limit, nofollow)
    if environment.autoescape:
        rv = Markup(rv)
    return rv
示例#13
0
def do_join(eval_ctx, value, d=u'', attribute=None):
    """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 = imap(make_attrgetter(eval_ctx.environment, attribute), value)

    # no automatic escaping?  joining is a lot eaiser then
    if not eval_ctx.autoescape:
        return text_type(d).join(imap(text_type, 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] = text_type(item)
        if do_escape:
            d = escape(d)
        else:
            d = text_type(d)
        return d.join(value)

    # no html involved, to normal joining
    return soft_unicode(d).join(imap(soft_unicode, value))
示例#14
0
def inc_filter(env, key, value=1, result='value', reset=False):
    """
    Count ocurrences of key.
    Stores the counter on Jinja's environment.
        >>> class Env: pass
        >>> env = Env()
        >>> inc_filter(env, 'x')
        1
        >>> inc_filter(env, 'x')
        2
        >>> inc_filter(env, 'y')
        1
        >>> inc_filter(env, 'x')
        3
        >>> inc_filter(env, 'x', reset=True)
        1
        >>> inc_filter(env, 'x')
        2
        >>> inc_filter(env, 'x', value=0, reset=True)
        0
        >>> inc_filter(env, 'x', result=None)
        >>> inc_filter(env, 'x', result=False)
        u''
        >>> inc_filter(env, 'x', result='key')
        'x'
        >>> inc_filter(env, 'x')
        4
    """
    if not hasattr(env, 'counters'):
        env.counters = defaultdict(int)

    if reset:
        env.counters[key] = 0

    env.counters[key] += value

    if result == 'key':
        return key
    elif result == 'value':
        return env.counters[key]
    elif result == None:
        return None
    else:
        return soft_unicode('')
示例#15
0
def do_join(eval_ctx, value, d = u'', attribute = None):
    if attribute is not None:
        value = imap(make_attrgetter(eval_ctx.environment, attribute), value)
    if not eval_ctx.autoescape:
        return unicode(d).join(imap(unicode, value))
    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] = unicode(item)

        if do_escape:
            d = escape(d)
        else:
            d = unicode(d)
        return d.join(value)
    return soft_unicode(d).join(imap(soft_unicode, value))
示例#16
0
def do_trim(value):
    return soft_unicode(value).strip()
示例#17
0
def do_trim(value):
    return soft_unicode(value).strip()
def format_string(string, pattern):
    """
    formats the string with the value passed to it
    basicaly the reverse order of standard "format()"
    """
    return soft_unicode(pattern) % (string)
示例#19
0
def do_capitalize(s):
    """Capitalize a value. The first character will be uppercase, all others
    lowercase.
    """
    return soft_unicode(s).capitalize()
示例#20
0
def do_lower(s):
    return soft_unicode(s).lower()
示例#21
0
def do_format(value, *args, **kwargs):
    if args and kwargs:
        raise FilterArgumentError(
            "can't handle positional and keyword arguments at the same time")
    return soft_unicode(value) % (kwargs or args)
示例#22
0
def do_lower(s):
    return soft_unicode(s).lower()
示例#23
0
def do_capitalize(s):
    """Capitalize a value. The first character will be uppercase, all others
    lowercase.
    """
    return soft_unicode(s).capitalize()
示例#24
0
def do_upper(s):
    """Convert a value to uppercase."""
    return soft_unicode(s).upper()
示例#25
0
def do_upper(s):
    return soft_unicode(s).upper()
示例#26
0
def do_title(s):
    return soft_unicode(s).title()
示例#27
0
def do_capitalize(s):
    return soft_unicode(s).capitalize()
示例#28
0
def do_format(value, *args, **kwargs):
    if args and kwargs:
        raise FilterArgumentError("can't handle positional and keyword arguments at the same time")
    return soft_unicode(value) % (kwargs or args)
示例#29
0
文件: filters.py 项目: nicko170/jinja
def do_trim(value, chars=None):
    """Strip leading and trailing characters, by default whitespace."""
    return soft_unicode(value).strip(chars)
示例#30
0
def do_upper(s):
    """Convert a value to uppercase."""
    return soft_unicode(s).upper()
示例#31
0
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 soft_unicode(s).title()
示例#32
0
def do_lower(s):
    """Convert a value to lowercase."""
    return soft_unicode(s).lower()
示例#33
0
def do_title(s):
    return soft_unicode(s).title()
示例#34
0
def do_upper(s):
    return soft_unicode(s).upper()
示例#35
0
def trim_filter(value, what=None):
    """Strip leading and trailing whitespace or other specified character.

    Adapted from Jinja2's builtin ``trim`` filter.
    """
    return soft_unicode(value).strip(what)
示例#36
0
def do_capitalize(s):
    return soft_unicode(s).capitalize()
示例#37
0
def do_lower(s):
    """Convert a value to lowercase."""
    return soft_unicode(s).lower()
示例#38
0
def map_format(value, pattern):
    """
    e.g.
    "{{ groups['metad']|map('map_format', '%s:9559')|join(',') }}"
    """
    return soft_unicode(pattern) % (value)
示例#39
0
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 soft_unicode(s).title()
示例#40
0
def do_trim(value):
    """Strip leading and trailing whitespace."""
    return soft_unicode(value).strip()
示例#41
0
def do_trim(value):
    """Strip leading and trailing whitespace."""
    return soft_unicode(value).strip()
示例#42
0
def format_string(string, pattern):
    """
    formats the string with the value passed to it
    basicaly the reverse order of standard "format()"
    """
    return soft_unicode(pattern) % (string)