tera icon indicating copy to clipboard operation
tera copied to clipboard

Add support for SystemTime

Open rogerta opened this issue 2 years ago • 3 comments

Tera does not support the type std::time::SystemTime along with the | date filter. For example, writing a template with the the expression {{ last_used | date }}, where last_used is of type std::time::SystemTime, generates the following runtime error when using Rocket:

   >> Error rendering Tera template 'info'.
   >> Failed to render 'info'
   >> Filter call 'date' failed
   >> Filter `date` received an incorrect type for arg `value`: got `Object {"nanos_since_epoch": Number(344630894), "secs_since_epoch": Number(1673625538)}` but expected i64|u64|String
   >> Template 'info' failed to render.
   >> Outcome: Failure

Versions:

$ rustup --version
rustup 1.25.1 (bb60b1e89 2022-07-12)
info: This is the version for the rustup toolchain manager, not the rustc compiler.
info: The currently active `rustc` version is `rustc 1.66.1 (90743e729 2023-01-10)`

From Cargo.toml:

rocket = { version = "0.5.0-rc.2", features = [ "json", "secrets" ] }
rocket_dyn_templates = { version = "0.1.0-rc.2", features = [ "tera" ] }
serde = { version = "1.0.145", features = ["derive"] }
serde_json = "1.0.87"
tera = { features = [ "builtins" ] }

rogerta avatar Jan 13 '23 21:01 rogerta

You need to pass the actual timestamp you want to format, not the object. So something like {{ last_used.secs_since_epoch | date }}

Keats avatar Jan 15 '23 21:01 Keats

Yeah that's what I'm doing right now as a workaround. However, SystemTime is not localized, it's always UTC. I wonder if it would be better to add chrono::DateTime support instead?

rogerta avatar Jan 16 '23 15:01 rogerta

You can format the timestamp in a given timezone/format with the date filter. You can also use the locale with the https://github.com/Keats/tera/blob/master/Cargo.toml#L49 feature enabled

Keats avatar Jan 16 '23 17:01 Keats