Lorem ipsum dolor sit amet, consectetur"
+ " adipiscing elit & sed do eiusmod tempor.
",
+ "size": i * 98765,
+ "views": i * 1234567,
+ }
+ for i in range(50)
+ ]
+ },
+)
+
scenario(
"engine_e2e",
"Hi {{ name }}! {% for n in nums %}{{ n }}{% endfor %}",
diff --git a/benchmarks/jinja2_bench.py b/benchmarks/jinja2_bench.py
index eaa59d9..d3bab6d 100644
--- a/benchmarks/jinja2_bench.py
+++ b/benchmarks/jinja2_bench.py
@@ -202,14 +202,21 @@ def jinja(name, source, loader=None):
"{% for a in arts %}
{{ a.body|striptags|truncatewords(12) }}
"
"{{ a.views|intcomma }} views{% endfor %}",
)
+jinja(
+ "truncate_html_sizes",
+ "{% for a in arts %}
{{ a.body|truncatewords_html(8) }}
"
+ "
{{ a.body|truncatechars_html(40) }}
"
+ "{{ a.size|filesizeformat }}, {{ a.views|intword }} views{% endfor %}",
+)
jinja("engine_e2e", "Hi {{ name }}! {% for n in nums %}{{ n }}{% endfor %}")
# Django filters with no same-output Jinja2 builtin. Jinja2's own ``urlize``,
# ``striptags`` and ``truncate`` behave differently, so Django's replace them.
_DJANGO_FILTERS = (
- "capfirst date default_if_none floatformat linebreaksbr striptags time"
- " truncatechars truncatewords urlize urlizetrunc"
+ "capfirst date default_if_none filesizeformat floatformat linebreaksbr striptags"
+ " time truncatechars truncatechars_html truncatewords truncatewords_html urlize"
+ " urlizetrunc"
).split()
@@ -226,7 +233,7 @@ def _django_filter(fn):
def build_jinja_env(loader):
import jinja2
- from django.contrib.humanize.templatetags.humanize import intcomma
+ from django.contrib.humanize.templatetags.humanize import intcomma, intword
from django.template import defaultfilters
from django.urls import reverse
from django.utils.translation import gettext, ngettext
@@ -243,6 +250,7 @@ def build_jinja_env(loader):
for name in _DJANGO_FILTERS:
env.filters[name] = _django_filter(getattr(defaultfilters, name))
env.filters["intcomma"] = intcomma
+ env.filters["intword"] = intword
env.globals["url"] = lambda name, *args: reverse(name, args=args)
env.globals["one_param"] = one_param
return env
diff --git a/src/filters/floatformat.rs b/src/filters/floatformat.rs
index 4a78591..0881700 100644
--- a/src/filters/floatformat.rs
+++ b/src/filters/floatformat.rs
@@ -294,7 +294,7 @@ fn exact_str<'a>(v: &'a Bound<'_, PyAny>) -> Option<&'a str> {
/// `formats.number_format(number, decimal_pos, use_l10n, force_grouping)`
/// for a `str` number; `None` → Python.
-fn number_format(
+pub(super) fn number_format(
rc: &mut Rctx<'_>,
number: &str,
decimal_pos: usize,
diff --git a/src/filters/humanize.rs b/src/filters/humanize.rs
index 9acfede..425b343 100644
--- a/src/filters/humanize.rs
+++ b/src/filters/humanize.rs
@@ -567,3 +567,102 @@ pub(crate) fn ordinal<'py>(
}
py_ordinal(py)?.call1((input,).into_pyobject(py)?.add_args(args)?)
}
+
+/// The stock Python `intword` (fallback for everything but plain ints).
+fn py_intword(py: Python<'_>) -> PyResult<&Bound<'_, PyAny>> {
+ static F: PyOnceLock> = PyOnceLock::new();
+ Ok(F.get_or_try_init(py, || -> PyResult> {
+ Ok(py
+ .import("django.contrib.humanize.templatetags.humanize")?
+ .getattr("intword")?
+ .unbind())
+ })?
+ .bind(py))
+}
+
+/// `True` while the humanize module's `ngettext` / `defaultfilters` globals
+/// are the stock objects (the `intword_converters` lambdas and `intword`
+/// resolve both at call time).
+fn intword_globals_stock(py: Python<'_>) -> PyResult {
+ static G: PyOnceLock<(Py, Py, Py)> = PyOnceLock::new();
+ let (globals, ngettext, defaultfilters) = G.get_or_try_init(py, || -> PyResult<_> {
+ Ok((
+ py.import("django.contrib.humanize.templatetags.humanize")?
+ .dict()
+ .unbind(),
+ py.import("django.utils.translation")?
+ .getattr("ngettext")?
+ .unbind(),
+ py.import("django.template.defaultfilters")?
+ .into_any()
+ .unbind(),
+ ))
+ })?;
+ let globals = globals.bind(py);
+ let same = |name: &str, f: &Py| -> PyResult {
+ Ok(globals.get_item(name)?.is_some_and(|g| g.is(f.bind(py))))
+ };
+ Ok(same("ngettext", ngettext)? && same("defaultfilters", defaultfilters)?)
+}
+
+/// `intword(value)` for an exact `int` below 2**53 in magnitude (so
+/// `value / 10**exponent` is one correctly rounded float division, as in
+/// Python): the converter's `ngettext` through `Translator`,
+/// `floatformat(new_value, 1)` through the native `floatformat`. Other
+/// inputs or patched module globals take the Python function.
+pub(crate) fn intword<'py>(
+ rc: &mut Rctx<'py>,
+ input: &Bound<'py, PyAny>,
+ args: &[Bound<'py, PyAny>],
+ _ae: Option,
+) -> PyResult> {
+ const CONVERTERS: [(i32, &str); 4] = [
+ (6, "%(value)s million"),
+ (9, "%(value)s billion"),
+ (12, "%(value)s trillion"),
+ (15, "%(value)s quadrillion"),
+ ];
+ let py = input.py();
+ if args.is_empty() && input.is_exact_instance_of::() {
+ if let Ok(n) = input.extract::() {
+ let abs = n.unsigned_abs();
+ if abs < 1_000_000 {
+ return Ok(input.clone());
+ }
+ if abs < 1 << 53 && intword_globals_stock(py)? {
+ #[allow(clippy::cast_precision_loss)] // exact below 2**53
+ let (value, abs_f) = (n as f64, abs as f64);
+ for (exponent, msgid) in CONVERTERS {
+ let large = 10f64.powi(exponent);
+ if abs_f < large * 1000.0 {
+ let new_value = value / large;
+ // `round_away_from_one`: ROUND_UP of `new_value - 1`.
+ let y = new_value - 1.0;
+ let r = if y.fract() == 0.0 {
+ y
+ } else if y > 0.0 {
+ y.ceil()
+ } else {
+ y.floor()
+ };
+ #[allow(clippy::cast_possible_truncation)] // |r| < 1e3
+ let count = (r as i64 + 1).abs();
+ let ff = super::floatformat::floatformat(
+ rc,
+ &pyo3::types::PyFloat::new(py, new_value).into_any(),
+ &[1i64.into_pyobject(py)?.into_any()],
+ None,
+ )?
+ .str()?;
+ let tmpl = super::Translator::new(py).cached(msgid, msgid, Some(count))?;
+ if let Some(s) = super::substitute(&tmpl, "%(value)s", ff.to_str()?) {
+ return Ok(PyString::new(py, &s).into_any());
+ }
+ break;
+ }
+ }
+ }
+ }
+ }
+ py_intword(py)?.call1((input,).into_pyobject(py)?.add_args(args)?)
+}
diff --git a/src/filters/mod.rs b/src/filters/mod.rs
index 93f6798..5076237 100644
--- a/src/filters/mod.rs
+++ b/src/filters/mod.rs
@@ -23,6 +23,9 @@
//! `urlize` are full ports with per-branch detection and Python fallbacks
//! (see their modules; a mocked `Urlizer` disables the native path).
+use std::cell::RefCell;
+use std::collections::HashMap;
+
use pyo3::prelude::*;
use pyo3::sync::PyOnceLock;
use pyo3::type_object::PyTypeInfo;
@@ -38,6 +41,7 @@ mod lists;
mod misc;
mod numbers;
mod strings;
+mod truncate_html;
mod urlize;
/// A native built-in filter.
@@ -56,9 +60,7 @@ pub type NativeFn = for<'py> fn(
) -> PyResult>;
/// Native implementation for a stock built-in name, `None` for filters that
-/// stay bridged (`filesizeformat`, `dictsort`,
-/// `dictsortreversed`, `truncatechars_html`, `truncatewords_html`) or
-/// unknown names.
+/// stay bridged (`dictsort`, `dictsortreversed`) or unknown names.
pub(crate) fn lookup(name: &str) -> Option {
match name {
// strings
@@ -72,6 +74,8 @@ pub(crate) fn lookup(name: &str) -> Option {
"title" => Some(strings::title),
"truncatechars" => Some(strings::truncatechars),
"truncatewords" => Some(strings::truncatewords),
+ "truncatechars_html" => Some(truncate_html::truncatechars_html),
+ "truncatewords_html" => Some(truncate_html::truncatewords_html),
"upper" => Some(strings::upper),
"lower" => Some(strings::lower),
"wordcount" => Some(strings::wordcount),
@@ -93,6 +97,7 @@ pub(crate) fn lookup(name: &str) -> Option {
"divisibleby" => Some(numbers::divisibleby),
"pluralize" => Some(numbers::pluralize),
"floatformat" => Some(floatformat::floatformat),
+ "filesizeformat" => Some(numbers::filesizeformat),
// html strings
"escape" => Some(html::escape_filter),
"escapeseq" => Some(html::escapeseq),
@@ -155,12 +160,23 @@ fn humanize_native(func: &Bound<'_, PyAny>) -> Option {
let qualname: String = func.getattr("__qualname__").and_then(|m| m.extract()).ok()?;
match qualname.as_str() {
"intcomma" => Some(humanize::intcomma),
+ "intword" => Some(humanize::intword),
"naturaltime" => Some(humanize::naturaltime),
"ordinal" => Some(humanize::ordinal),
_ => None,
}
}
+/// `tmpl % arg` for a translated template whose only `%` starts `key`
+/// (`"%(size)d"`, `"%s"`, ...), with `value` already formatted the way
+/// that conversion would; `None` for any other template shape (the caller
+/// then runs the Python filter, which formats or raises like stock).
+pub(crate) fn substitute(tmpl: &Bound<'_, PyAny>, key: &str, value: &str) -> Option {
+ let t = tmpl.cast_exact::().ok()?.to_str().ok()?;
+ let pos = t.find(key)?;
+ (t.matches('%').count() == 1).then(|| format!("{}{value}{}", &t[..pos], &t[pos + key.len()..]))
+}
+
/// `True` iff `e` is an instance of exception type `T` (Python class check).
pub(crate) fn is_err(py: Python<'_>, e: &PyErr) -> bool {
e.is_instance_of::(py)
@@ -538,6 +554,56 @@ impl<'py> Translator<'py> {
}
}
+ /// `ngettext(singular, plural, n)` / `gettext(singular)` (`n = None`)
+ /// for static msgids, memoized per translation object: a
+ /// `DjangoTranslation`'s catalog never changes after construction, and
+ /// a reload builds new objects, so results are keyed on the object
+ /// itself (held, so its identity can't be reused). `trans_null` and the
+ /// Python fallback paths are not memoized.
+ pub(crate) fn cached(
+ &self,
+ singular: &'static str,
+ plural: &'static str,
+ n: Option,
+ ) -> PyResult> {
+ type Memo = Option<(Py, HashMap<(&'static str, Option), Py>)>;
+ thread_local! {
+ static MEMO: RefCell = const { RefCell::new(None) };
+ }
+ let py = self.py;
+ let fname = if n.is_some() { "ngettext" } else { "gettext" };
+ let compute = || match n {
+ Some(n) => self.ngettext(singular, plural, &n.into_pyobject(py)?.into_any()),
+ None => self.gettext(singular),
+ };
+ let Some(TransObj::Real(t)) = self.obj(fname, n.is_some())? else {
+ return compute();
+ };
+ let key = (singular, n);
+ let hit = MEMO.with(|m| match &*m.borrow() {
+ Some((obj, map)) if obj.bind(py).is(&t) => map.get(&key).map(|v| v.clone_ref(py)),
+ _ => None,
+ });
+ if let Some(v) = hit {
+ return Ok(v.into_bound(py));
+ }
+ let v = compute()?;
+ MEMO.with(|m| {
+ let mut m = m.borrow_mut();
+ match &mut *m {
+ Some((obj, map)) if obj.bind(py).is(&t) && map.len() < 4096 => {
+ map.insert(key, v.clone().unbind());
+ }
+ _ => {
+ let mut map = HashMap::new();
+ map.insert(key, v.clone().unbind());
+ *m = Some((t.clone().unbind(), map));
+ }
+ }
+ });
+ Ok(v)
+ }
+
/// `npgettext(context, singular, plural, number)`.
pub(crate) fn npgettext(
&self,
diff --git a/src/filters/numbers.rs b/src/filters/numbers.rs
index a5fde3e..2b1464e 100644
--- a/src/filters/numbers.rs
+++ b/src/filters/numbers.rs
@@ -1,7 +1,8 @@
//! Integer filters of `django.template.defaultfilters` (native ports).
use pyo3::prelude::*;
-use pyo3::types::PyString;
+use pyo3::sync::PyOnceLock;
+use pyo3::types::{PyInt, PyString};
use crate::render::context::Rctx;
use crate::render::value::helpers;
@@ -137,3 +138,85 @@ pub(crate) fn pluralize<'py>(
Err(e) => Err(e),
}
}
+
+/// The stock Python `filesizeformat` (fallback for everything but plain
+/// ints).
+fn py_filesizeformat(py: Python<'_>) -> PyResult<&Bound<'_, PyAny>> {
+ static F: PyOnceLock> = PyOnceLock::new();
+ Ok(F.get_or_try_init(py, || -> PyResult> {
+ Ok(py
+ .import("django.template.defaultfilters")?
+ .getattr("filesizeformat")?
+ .unbind())
+ })?
+ .bind(py))
+}
+
+/// `filesizeformat(bytes_)` for an exact `int` below 2**53 in magnitude
+/// (so `bytes_ / KB` etc. are exact float divisions and `round(x, 1)` is
+/// integer arithmetic on the tenths). The unit templates go through
+/// `Translator`, `number_format(round(x, 1), 1)` through the native
+/// `floatformat` formatter; other inputs take the Python filter.
+pub(crate) fn filesizeformat<'py>(
+ rc: &mut Rctx<'py>,
+ input: &Bound<'py, PyAny>,
+ _args: &[Bound<'py, PyAny>],
+ _ae: Option,
+) -> PyResult> {
+ let py = input.py();
+ if input.is_exact_instance_of::() {
+ if let Ok(n) = input.extract::() {
+ if n.unsigned_abs() < 1 << 53 {
+ if let Some(s) = native_filesizeformat(rc, n)? {
+ return Ok(PyString::new(py, &s).into_any());
+ }
+ }
+ }
+ }
+ py_filesizeformat(py)?.call1((input,))
+}
+
+fn native_filesizeformat(rc: &mut Rctx<'_>, n: i64) -> PyResult
",
+ "
self
closing tags",
+ "stray end tags unclosed nested",
+ "