Skip to content

Instantly share code, notes, and snippets.

@jimmycuadra
Created July 12, 2018 07:21
Show Gist options
  • Save jimmycuadra/64b3c89f03c1559d843376b0f1b1665b to your computer and use it in GitHub Desktop.
Save jimmycuadra/64b3c89f03c1559d843376b0f1b1665b to your computer and use it in GitHub Desktop.
Tilt-like template engine abstraction
extern crate askama; // doensn't really work cause it creates a struct for each template at compile time
extern crate handlebars;
extern crate liquid;
extern crate maud; // doesn't really work cause it creates templates from within Rust code with a macro
extern crate serde;
extern crate tera;
use std::fmt::Display;
use serde::Serialize;
/// Types that can render templates with data.
pub trait Render<Data> {
type Output: Display;
type Error;
fn new() -> Self;
fn render_inline<S>(&self, source: S, data: &Data) -> Result<Self::Output, Self::Error> where S: AsRef<str>;
}
/// A registry of named templates.
pub struct Registry<T> {
inner: T
}
impl<Data> Render<Data> for Registry<handlebars::Handlebars> where Data: Serialize {
type Output = String;
type Error = handlebars::TemplateRenderError;
fn new() -> Self {
Self {
inner: handlebars::Handlebars::new(),
}
}
fn render_inline<S>(&self, source: S, data: &Data) -> Result<Self::Output, Self::Error> where S: AsRef<str> {
self.inner.render_template(source.as_ref(), data)
}
}
impl Render<liquid::Object> for Registry<liquid::Parser> {
type Output = String;
type Error = liquid::compiler::Error;
fn new() -> Self {
Self {
inner: liquid::Parser::default(),
}
}
fn render_inline<S>(&self, source: S, data: &liquid::Object) -> Result<Self::Output, Self::Error> where S: AsRef<str> {
self.inner.parse(source.as_ref())?.render(data)
}
}
impl<Data> Render<Data> for Registry<tera::Tera> where Data: Serialize {
type Output = String;
type Error = tera::Error;
fn new() -> Self {
Self {
inner: tera::Tera::default(),
}
}
fn render_inline<S>(&self, source: S, data: &Data) -> Result<Self::Output, Self::Error> where S: AsRef<str> {
tera::Tera::one_off(source.as_ref(), data, true)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment