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)] #[derive(Default, Template)]
#[template(path = "index.html")] #[template(path = "index.html")]
struct Document { struct Document {
// TODO: This is duplicated. Reuse the Fragment struct. But how? fragment: Option<Fragment>,
users: Option<Vec<User>>,
} }
#[get("/")] #[get("/")]
async fn index() -> actix_web::Result<impl Responder> { 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"))) Ok(Html(page.render().expect("Valid template")))
} }
@@ -52,7 +51,8 @@ async fn users(req: HttpRequest) -> actix_web::Result<impl Responder> {
} }
None => { None => {
// Render the whole document // 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> <p>A new old way to build web applications</p>
</hgroup> </hgroup>
<table> <table>
{% if users.is_some() %}
{% include "fragment/user/table.html" %} {% match fragment %}
{% else %} {% when Some with (fragment) %}
<tr><td> {{ fragment|safe }}
<button hx-get="/user" hx-target="table" hx-push-url="true"> {% when None %}
Load data <tr><td>
</button> <button hx-get="/user" hx-target="table" hx-push-url="true">
</td></tr> Load data
{% endif %} </button>
</td></tr>
{% endmatch %}
</table> </table>
{% endblock %} {% endblock %}