Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

alternative "template reload" experience #977

Merged
merged 7 commits into from
Nov 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions examples/demo/src/initializers/view_engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,22 @@ impl Initializer for ViewEngineInitializer {
}

async fn after_routes(&self, router: AxumRouter, _ctx: &AppContext) -> Result<AxumRouter> {
#[allow(unused_mut)]
let mut tera_engine = engines::TeraView::build()?;
if std::path::Path::new(I18N_DIR).exists() {
let arc = ArcLoader::builder(&I18N_DIR, unic_langid::langid!("en-US"))
.shared_resources(Some(&[I18N_SHARED.into()]))
.customize(|bundle| bundle.set_use_isolating(false))
.build()
.map_err(|e| Error::string(&e.to_string()))?;
#[cfg(debug_assertions)]
tera_engine
.tera
.lock()
.expect("lock")
.register_function("t", FluentLoader::new(arc));

#[cfg(not(debug_assertions))]
tera_engine
.tera
.register_function("t", FluentLoader::new(arc));
Expand Down
2 changes: 1 addition & 1 deletion src/controller/middleware/cors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ impl Default for Cors {
}

fn default_allow_origins() -> Vec<String> {
vec!["*".to_string()]
vec!["any".to_string()]
}

fn default_allow_headers() -> Vec<String> {
Expand Down
47 changes: 26 additions & 21 deletions src/controller/views/engines.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,15 @@ const VIEWS_DIR: &str = "assets/views";

#[derive(Clone, Debug)]
pub struct TeraView {
#[cfg(debug_assertions)]
pub tera: std::sync::Arc<std::sync::Mutex<tera::Tera>>,

#[cfg(not(debug_assertions))]
pub tera: tera::Tera,

#[cfg(debug_assertions)]
pub view_dir: String,

pub default_context: tera::Context,
}

Expand Down Expand Up @@ -44,38 +52,35 @@ impl TeraView {
)?;
let ctx = tera::Context::default();
Ok(Self {
tera,
#[cfg(debug_assertions)]
view_dir: path.as_ref().to_string_lossy().to_string(),
#[cfg(debug_assertions)]
tera: std::sync::Arc::new(std::sync::Mutex::new(tera)),
#[cfg(not(debug_assertions))]
tera: tera,
default_context: ctx,
})
}
}

impl ViewRenderer for TeraView {
fn render<S: Serialize>(&self, key: &str, data: S) -> Result<String> {
#[cfg(debug_assertions)]
use std::borrow::BorrowMut;

let context = tera::Context::from_serialize(data)?;

// NOTE: this supports full reload of template for every render request.
// it means that you will see refreshed content without rebuild and rerun
// of the app.
// the code here is required, since Tera has no "build every time your render"
// mode, which would have been better.
// we minimize risk by flagging this in debug (development) builds only
// for now we leave this commented out, we propose people use `cargo-watch`
// we want to delay using un__safe as much as possible.
/*
#[cfg(debug_assertions)]
{
let ptr = std::ptr::addr_of!(self.tera);
let mut_ptr = ptr.cast_mut();
// fix this keyword
un__safe {
let tera = &mut *mut_ptr;
tera.full_reload()?;
}
}
*/
tracing::debug!(key = key, "Tera rendering in non-optimized debug mode");
#[cfg(debug_assertions)]
return Ok(self.tera.lock().expect("lock").borrow_mut().render_str(
&std::fs::read_to_string(Path::new(&self.view_dir).join(key))
.map_err(|_e| tera::Error::template_not_found(key))?,
&context,
)?);

Ok(self.tera.render(key, &context)?)
#[cfg(not(debug_assertions))]
return Ok(self.tera.render(key, &context)?);
}
}

Expand Down
4 changes: 4 additions & 0 deletions starters/saas/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading