From 7279dee47f7434c86e571471a955f8da1fa67950 Mon Sep 17 00:00:00 2001 From: Dan Alekseev Date: Sun, 7 Apr 2024 14:33:27 +0400 Subject: [PATCH] Small refactoring --- README.md | 6 +++--- axum-htmx-derive/src/boosted_by/boosted_by.rs | 17 ++++++++++------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 0ee6add..c7bad77 100644 --- a/README.md +++ b/README.md @@ -98,9 +98,7 @@ In addition to the HxBoosted extractor, the library provides macroses `hx_booste The macro input should have a `layout_fn`, and can have arguments passed from annotated function into `layout_fn`. The macro will call the `layout_fn` if the `HX-Boosted` header is not present, otherwise it will return the response directly. -```rust -#[hx_boosted_by(layout_fn, [arg1, agr2, ...])] -``` +`#[hx_boosted_by(layout_fn [, arg1, agr2, ...])]` If `layout_fn` is an async function, use `hx_boosted_by_async` instead. @@ -203,6 +201,8 @@ fn router_two() -> Router { ### Example: Macros ```rust +use axum::extract::Path; +use axum::response::Html; use axum_htmx::hx_boosted_by; #[hx_boosted_by(with_layout, page_title)] diff --git a/axum-htmx-derive/src/boosted_by/boosted_by.rs b/axum-htmx-derive/src/boosted_by/boosted_by.rs index ff72713..169625a 100644 --- a/axum-htmx-derive/src/boosted_by/boosted_by.rs +++ b/axum-htmx-derive/src/boosted_by/boosted_by.rs @@ -76,21 +76,24 @@ pub fn transform_using_template(input: MacroInput, template_fn: ItemFn) -> ItemF source_fn.sig.inputs.push(hx_boosted_input); // pop the last statement and wrap it with if-else - let modify_stmt = source_fn.block.stmts.pop().unwrap(); - let modify_stmt = quote!(#modify_stmt).to_string(); - let modify_args = input.fn_args.join(""); + let source_stmt = source_fn.block.stmts.pop().unwrap(); + let source_stmt = quote!(#source_stmt).to_string(); let new_fn_str = quote!(#template_fn) .to_string() .replace("layout_fn", input.layout_fn.as_str()) - .replace("result_boosted", modify_stmt.as_str()) - .replace("result_with_layout", modify_stmt.as_str()) - .replace(", fn_args", modify_args.as_str()); + .replace("result_boosted", source_stmt.as_str()) + .replace("result_with_layout", source_stmt.as_str()); + // add layout_args + let layout_args = input.fn_args.join(""); + let new_fn_str = new_fn_str.replace(", fn_args", layout_args.as_str()); + + // parse new_fn_str as ItemFn let new_fn: ItemFn = parse_str(new_fn_str.as_str()).unwrap(); - let new_fn_stmt = new_fn.block.stmts.first().unwrap().clone(); // push the new statement to source_fn + let new_fn_stmt = new_fn.block.stmts.first().unwrap().clone(); source_fn.block.stmts.push(new_fn_stmt); source_fn.to_owned()