refactor: render fragment explicitly

Instead of including the template for non-hx-requests, inject the
rendered fragment.
This commit is contained in:
2023-05-10 20:37:27 +02:00
parent 32f5afb10f
commit 4489a8a8e5
2 changed files with 15 additions and 13 deletions

View File

@@ -19,13 +19,12 @@ struct Fragment {
#[derive(Default, Template)]
#[template(path = "index.html")]
struct Document {
// TODO: This is duplicated. Reuse the Fragment struct. But how?
users: Option<Vec<User>>,
fragment: Option<Fragment>,
}
#[get("/")]
async fn index() -> actix_web::Result<impl Responder> {
let page = Document { users: None };
let page = Document { fragment: None };
Ok(Html(page.render().expect("Valid template")))
}
@@ -52,7 +51,8 @@ async fn users(req: HttpRequest) -> actix_web::Result<impl Responder> {
}
None => {
// Render the whole document
Ok(Html(Document { users }.render().expect("Valid template")))
let fragment = Some(Fragment { users });
Ok(Html(Document { fragment }.render().expect("Valid template")))
}
}
}

View File

@@ -6,14 +6,16 @@
<p>A new old way to build web applications</p>
</hgroup>
<table>
{% if users.is_some() %}
{% include "fragment/user/table.html" %}
{% else %}
{% match fragment %}
{% when Some with (fragment) %}
{{ fragment|safe }}
{% when None %}
<tr><td>
<button hx-get="/user" hx-target="table" hx-push-url="true">
Load data
</button>
</td></tr>
{% endif %}
{% endmatch %}
</table>
{% endblock %}