Coverage for jinjazzle/ext/string.py: 100%
27 statements
« prev ^ index » next coverage.py v7.6.10, created at 2025-01-24 22:03 +0000
« prev ^ index » next coverage.py v7.6.10, created at 2025-01-24 22:03 +0000
1"""
2Description
3-----------
5StringExtension provides the standard string functions.
8.. autoclass:: StringExtension
11.. py:function:: slugify(lhs, **kwargs)
13 Slugifies the value with python-slugify
15 https://pypi.org/project/python-slugify/
17 Make a slug from the given text.
19 :param text (str): initial text
20 :param entities (bool): converts html entities to unicode (foo & bar -> foo-bar)
21 :param decimal (bool): converts html decimal to unicode (Ž -> Ž -> z)
22 :param hexadecimal (bool): converts html hexadecimal to unicode (Ž -> Ž -> z)
23 :param max_length (int): output string length
24 :param word_boundary (bool): truncates to end of full words (length may be shorter than max_length)
25 :param save_order (bool): if parameter is True and max_length > 0 return whole words in the initial order
26 :param separator (str): separator between words
27 :param stopwords (iterable): words to discount
28 :param regex_pattern (str): regex pattern for disallowed characters
29 :param lowercase (bool): activate case sensitivity by setting it to False
30 :param replacements (iterable): list of replacement rules e.g. [['|', 'or'], ['%', 'percent']]
31 :param allow_unicode (bool): allow unicode characters
33 Available as a function and a filter. For the latter case, *lhs* is automatically specified as the left hand side of the filter.
35 .. code-block:: jinja
37 # Returns "hello-world"
38 {{ "Hello, World!" | slugify }}
40 # Returns "hello_world"
41 {{ slugify("Hello, World!", separator="_") }}
44.. py:function:: random_string(length, punctuation=False, lowercase=True, uppercase=True, digits=True)
46 Return a random string of length characters from the character sets selected.
48 Uses :py:func:`secrets.choice` module to generate random strings.
50 :param punctuation: Use the :py:data:`string.punctuation` set.
51 :param lowercase: Use the :py:data:`string.ascii_lowercase` set.
52 :param uppercase: Use the :py:data:`string.ascii_uppercase` set.
53 :param digits: Use the :py:data:`string.digits` set.
55 .. code-block:: jinja
57 {{ random_string(8, punctuation=True) }}
58"""
60import string
61from secrets import choice
63from jinja2.ext import Extension
64from slugify import slugify as pyslugify
67def _slugify(text, **kwargs):
68 """
69 Slugifies the value.
70 https://pypi.org/project/python-slugify/
72 Make a slug from the given text.
73 :param text (str): initial text
74 :param entities (bool): converts html entities to unicode (foo & bar -> foo-bar)
75 :param decimal (bool): converts html decimal to unicode (Ž -> Ž -> z)
76 :param hexadecimal (bool): converts html hexadecimal to unicode (Ž -> Ž -> z)
77 :param max_length (int): output string length
78 :param word_boundary (bool): truncates to end of full words (length may be shorter than max_length)
79 :param save_order (bool): if parameter is True and max_length > 0 return whole words in the initial order
80 :param separator (str): separator between words
81 :param stopwords (iterable): words to discount
82 :param regex_pattern (str): regex pattern for disallowed characters
83 :param lowercase (bool): activate case sensitivity by setting it to False
84 :param replacements (iterable): list of replacement rules e.g. [['|', 'or'], ['%', 'percent']]
85 :param allow_unicode (bool): allow unicode characters
86 :return (str): slugify text
87 """
88 return pyslugify(text, **kwargs)
91def _random_string(length, punctuation=False, lowercase=True, uppercase=True, digits=True):
92 if not isinstance(length, int) or length <= 0:
93 raise ValueError("length must be a positive integer")
95 corpus = ""
96 if lowercase:
97 corpus += string.ascii_lowercase
98 if uppercase:
99 corpus += string.ascii_uppercase
100 if digits:
101 corpus += string.digits
102 if punctuation:
103 corpus += string.punctuation
104 if len(corpus) == 0:
105 raise ValueError("corpus is empty, no characters to choose from")
107 return "".join(choice(corpus) for _ in range(length))
110# pylint: disable=abstract-method
111class StringExtension(Extension):
112 """
113 Jinja2 extension for string manipulation.
114 """
116 def __init__(self, environment):
117 """
118 Jinja2 Extension constructor.
119 """
120 super().__init__(environment)
122 environment.globals.update(random_string=_random_string)
124 environment.filters["slugify"] = _slugify
125 environment.globals.update(slugify=_slugify)