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

Implement TideTeraExt for Arc<RwLock<Tera>> #9

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

rjframe
Copy link

@rjframe rjframe commented Sep 1, 2021

This allows sharing the Tera instance across sync boundaries.

I have not run benchmarks, but the only time reading the Tera object will block is while templates are being reloaded, so any speed reduction should be minimal and will only be paid by people using the feature.

This PR does make async-std a dependency -- since Tide requires it I'm assuming that's acceptable, though this PR could easily be placed behind a feature flag.

My use case is hot-reloading templates with notify:

async fn main() -> anyhow::Result<()> {
    let mut templates = match Tera::new("views/**/*.html")?;
    templates.register_filter("filter_name", filter_function); // etc

    let templates = Arc::new(RwLock::new(templates));

    let mut app = tide::with_state(templates.clone());

    AuthenticationService::with_state(templates.clone())
        .at("/")
        .register(&mut app);
    UserProfileService::with_state(templates.clone())
        .at("/profile")
        .register(&mut app);

    let mut template_watcher =
        RecommendedWatcher::new(move |result: Result<Event, Error>| {
            let event = result.unwrap();
            if event.kind.is_modify() {
                let mut templ = task::block_on(templates.write());
                if let Err(e) = templ.full_reload() {
                    log::error!("Error reloading template: {:?}", e);
                }
            }
        });

    template_watcher.watch(Path::new("views"), RecursiveMode::Recursive)?;

    app.listen("localhost:8080").await?;
    Ok(())
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant