Comments (8)
The format
filter as implemented in jinja2 is redundant anyway. If I could, I would deprecate and finally remove it, but mitsuhiko would not let me break backwards compatibility. Whenever I have to format a string in a template, I use the modulo operator inline.
{{ '%d' % x }}
{{ '%s:%d' % (x, y) }}
{{ '%(foo)s' % {'foo': 'bar'} }}
Written that way, the code is less, simpler and more readable. Also note that using the modulo operator instead of the format
filter results in more efficient Python code, when the template is compiled.
>>> print env.compile("{{ '%d'|format(x) }}", raw=True)
from __future__ import division
from jinja2.runtime import LoopContext, TemplateReference, Macro, Markup, TemplateRuntimeError, missing, concat, escape, markup_join, unicode_join, to_string, identity, TemplateNotFound
name = None
def root(context, environment=environment):
l_x = context.resolve('x')
t_1 = environment.filters['format']
if 0: yield None
yield to_string(t_1('%d', l_x))
blocks = {}
debug_info = '1=9'
>>> print env.compile("{{ '%d' % x }}", raw=True)
from __future__ import division
from jinja2.runtime import LoopContext, TemplateReference, Macro, Markup, TemplateRuntimeError, missing, concat, escape, markup_join, unicode_join, to_string, identity, TemplateNotFound
name = None
def root(context, environment=environment):
l_x = context.resolve('x')
if 0: yield None
yield to_string(('%d' % l_x))
blocks = {}
debug_info = '1=8'
Therefor I don't like the idea of adding another useless filter for formatting values, as that can also be accomplished the same, more elegant way by using the modulo operator.
from jinja.
{{ '%0.2f' % vvv|float }}
... or if you prefer the format
filter syntax ...
{{ '%0.2f'|format(vvv|float) }}
from jinja.
In my opinion the modulo operator variant is more readable than using the built-in format
or your pyformat
filter. That's because of it requires less code to read (and write). Also imagine a more sophisticated example, where you need to format a string with multiple values:
{{ '%i points (%0.2f%%)' % (points, total / points * 100) }}
Using pyformat
that code would look like that:
{{ points|pyformat('i') + 'points (' + (total / points * 100)|pyformat('0.2f') + '%)' }}
Do you still think that this it more readable?
I agree that the built-in format
filter breaks the information flow concept of filters. And also it is less efficient and requires more code to write compared to the module operator. But the modulo operator is not a filter, but an operator. So nobody expects that the information flow works like it does for filters.
The problems with adding another filter for string formatting, that works like your pyformat
filter, are:
- It is less flexible than the built-in
format
filter and the modulo operator. - It is just as inefficient as the built-in
format
filter. - Having three ways (
pyformat
,format
, modulo operator) to do the same thing is even worth than having two ways. - Users might be confused about the presence of two filters for string formatting, in particular because of the name "pyformat" is anything but self-explanatory, in my opinion. Also note that a lot of template authors, don't know anything about Python.
from jinja.
imagine the situation:
a value that I hope it's a number, but it could be None.
vvv | float | pyformat("0.2f")
how would you do this, using the modulo operator?
from jinja.
but this way the flow of information goes less linearly, instead of left to right (1, 2, 3) it goes middle to right to left (2, 3, 1). I understand your argument for speed, but readability is also worth considering...
from jinja.
well, I would write it like this:
... {{ points|pyformat('i') }} points ({{ total / points * 100)|pyformat('0.2f')}}%) ...
but I agree, in this case the single use of %
operator makes it more readable.
from jinja.
Here's a simple approach with a user-defined filter. If the overall filter behavior of this appeals to you, one of us could easily add to Jinja standard filters and make a pull request. Your thoughts on this?
(1) example of a message to be interpolated -- a custom flask-security error message:
SECURITY_MSG_CONFIRMATION_REQUIRED = ('This email address has not been confirmed. '\
'Please click on the link in the email we sent you. To receive the confirmation '\
'email again, <a href="{0.url_root}confirm">click here</a>.', 'error')
(2) custom filter defined in a flask app, for example:
def _jinja_interp(text, obj):
return text.format(obj)
app.jinja_env.filters['interp'] = _jinja_interp
(3) filter as used used in a Jinja template:
{% for error in field.errors %}
... other stuff ....
{{ error | interp(request) | safe }}
{% endfor %}
This allows string interpolation via a filter, given a dictionary to interpolate from -- exact analog of 'string {placeholder}'.format(**some_dict)
in typical Python. Can be filter-piped on to subsequent filters.
from jinja.
I think the pyformat
filter is unlikely to get implemented/merged.
from jinja.
Related Issues (20)
- unique filter doesn't work when chain with map filter in async variant HOT 1
- DebugUndefined does not retain filters in variable HOT 1
- injecting tokens in filter_stream fails with "expected token end of print statement"
- `select_autoescape` default value for `default_for_string` should be `False`
- .get_template() not work with path Windows slashes (\). HOT 1
- Cannot preserve types in templating context HOT 2
- Doesn't parse HTML multi escape sequence codes HOT 2
- Autoescape does not work well across blocks/inheritance
- Test failures with Python 3.13.0a1 HOT 3
- Property Template::is_up_to_date breaks type hint contract HOT 2
- NativeEnvironment casts integer strings to integer -- intended behavior? HOT 2
- Otera, a Better name than jinja.. HOT 1
- Misleading error when attribute in getitem(obj, attr) throws AttributeError HOT 7
- Change github link to ssh in "contributing" docs HOT 3
- Help improve Syntax Highlight for Monaco-Editor HOT 1
- The `int` filter throws `OverflowError` when the incoming string looks like scientific notation HOT 3
- Most basic Jinja function is inconsistent / crashes if the template has `{{ obj.property }}` elements, and `obj` is `None` or property does not exist HOT 2
- Introducing `NeverUndefined` HOT 3
- Leading newline after `trans` block with Jinja trim options results in translation lookup failure
- Indent filter fails confusing if input is not string HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from jinja.