tera icon indicating copy to clipboard operation
tera copied to clipboard

Trouble referencing the context in the template

Open EdmundsEcho opened this issue 3 years ago • 2 comments

I've looked through the docs, examples and some of the issues that might point me the way. This all said, I'm at a loss to figure this out.

I can render a template with inserts. As soon as I include a variable I expect to get from the context, the template does not render as expected.

Template instantiation

// load the static template assets
lazy_static! {
    pub static ref TEMPLATES: Tera = {
        let tera = match Tera::new("tnc-app/assets/templates/**/*.html") {
            Ok(t) => {
                println!("📁 Parsing templates from dir: {:?}", env::current_dir());
                t
            },
            Err(e) => {
                println!("Parsing error(s): {}", e);
                ::std::process::exit(1);
            }
        };
        tera
    };
}

The endpoint handler that instantiates the context

#[debug_handler]
async fn homepage2() -> impl IntoResponse {
    let mut context = tera::Context::new();
    context.insert("ENDPOINT", &"https://here.net/auth/");
    context.insert("NAME", &"Bob");
    match TEMPLATES.render("homepage2.html", &context) {
        Ok(html) => Html(html).into_response(),
        Err(e) => {
            tracing::error!("Error:{}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("Failed to render template. Error: {}", e),
            )
                .into_response()
        }
    };
}

The template

It renders "Sorry..."

...
    <section id="login">
        {% set my_var = 2 %}
        {{ my_var }}
        {% if NAME %}
            {{ NAME }}
        {% else %}
            Sorry, NAME isn't defined.
        {% endif %}
    </section>
...

Any ideas what I should be looking out for to connect the context to the template?

- E

EdmundsEcho avatar Mar 25 '22 17:03 EdmundsEcho

I can't reproduce the template issue in https://tera.netlify.app/playground/ and the Rust code seems fine?

Keats avatar Mar 25 '22 19:03 Keats

Thank you for taking a look. How might I track the context through the various function calls?... the TEMPLATES.render() call is fails anytime it relies on a context.

Similarly, I should be able to print the String generated by render? (Before it's essentially cast to Html)

EdmundsEcho avatar Mar 25 '22 20:03 EdmundsEcho