Skip to content

Commit

Permalink
Add conveniant strfmt filter
Browse files Browse the repository at this point in the history
  • Loading branch information
christophehenry committed Oct 9, 2024
1 parent 13d7b1c commit 2ded4f2
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
43 changes: 43 additions & 0 deletions dsfr/templatetags/dsfr_tags.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import warnings
from typing import Iterable

from django import template
from django.conf import settings
from django.contrib.messages.constants import DEBUG, INFO, SUCCESS, WARNING, ERROR
Expand Down Expand Up @@ -1636,3 +1638,44 @@ def concatenate(value, arg):
def hyphenate(value, arg):
"""Concatenate value and arg with hyphens as separator, if neither is empty"""
return "-".join(filter(None, [str(value), str(arg)]))


@register.filter(is_safe=True)
def strfmt(args, format_string):
"""
Shortcup to [`str.format`](https://docs.python.org/3/library/stdtypes.html#str.format).
Usage:
```django
{{ ctx_variable|strfmt:"The sum of 1 + 2 is {}" }}
```
`ctx_variable` may either be a single argument or a list of arguments or a dict of args:
```python
def get_context_data(self, **kwargs):
return {
"format_args: [1 + 2, "awesome"]
"format_kwargs": {
"add_result": 1 + 2,
"result_feeling": "awesome",
}
}
```
```django
{{ format_args|strfmt:"The sum of 1 + 2 is {0} and it's {1}" }}
{{ format_kwargs|strfmt:"The sum of 1 + 2 is {add_result} and it's {result_feeling}" }}
```
"""
kwargs = {}
if isinstance(args, dict):
kwargs.update(args)
args = tuple()
if isinstance(args, Iterable) and not isinstance(args, str):
args = tuple(args)
else:
args = (str(args),)

return format_html(format_string, *args, **kwargs)
37 changes: 37 additions & 0 deletions dsfr/test/test_templatetags.py
Original file line number Diff line number Diff line change
Expand Up @@ -1193,3 +1193,40 @@ def test_numbers_can_be_hyphenated(self):
def test_numbers_and_string_can_be_hyphenated(self):
result = hyphenate("test", 3)
self.assertEqual(result, "test-3")


class StrfmtTestCase(SimpleTestCase):
def test_single_arg(self):
self.assertEqual(
"The sum of 1 + 2 is 3",
Template(
'{% load dsfr_tags %}{{ ctx_variable|strfmt:"The sum of 1 + 2 is {}" }}'
).render(Context({"ctx_variable": 1 + 2})),
)

def test_args(self):
self.assertEqual(
"The sum of 1 + 2 is 3 and it's awesome",
Template(
"{% load dsfr_tags %}"
"""{{ ctx_variable|strfmt:"The sum of 1 + 2 is {0} and it's {1}" }}"""
).render(Context({"ctx_variable": [1 + 2, "awesome"]})),
)

def test_single_kwargs(self):
self.assertEqual(
"The sum of 1 + 2 is 3 and it's awesome",
Template(
"{% load dsfr_tags %}"
"""{{ ctx_variable|strfmt:"The sum of 1 + 2 is {add_result} and it's {result_feeling}" }}"""
).render(
Context(
{
"ctx_variable": {
"add_result": 1 + 2,
"result_feeling": "awesome",
}
}
)
),
)

0 comments on commit 2ded4f2

Please sign in to comment.