From fc35a7ef7213fe262d72de7029563b42121e7279 Mon Sep 17 00:00:00 2001 From: hhaensel Date: Tue, 31 Oct 2023 17:16:36 +0100 Subject: [PATCH 1/2] support expressions in `@for` macro --- src/Elements.jl | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/src/Elements.jl b/src/Elements.jl index 6f69ed05..103071b6 100644 --- a/src/Elements.jl +++ b/src/Elements.jl @@ -7,6 +7,7 @@ module Elements import Genie using Stipple +using MacroTools import Genie.Renderer.Html: HTMLString, normal_element @@ -214,15 +215,39 @@ const var"@else" = var"@els" Generates `v-for` directive to render a list of items based on an array. -### Example +`@for` supports both js expressions as String or a Julia expression with Vectors or Dicts + +## Example +### Javascript ```julia -julia> p(" {{todo}} ", class="warning", @for(:"todo in todos")) -"

\n {{todo}} \n

\n" +julia> p(" {{todo}} ", class="warning", @for("todo in todos")) +\"\"\" +

+ {{todo}} +

+\"\"\" ``` +### Julia expression +```julia +julia> dict = Dict(:a => "b", :c => 4); +julia> ul(li("k: {{ k }}, v: {{ v }}, i: {{ i }}", @for((v, k, i) in dict))) +\"\"\" + +\"\"\" +``` +Note the inverted order of value, key and index compared to Stipple destructuring. +It is also possible to loop over `(v, k)` or `v`; index will always be zero-based """ macro recur(expr) + Base.isexpr(expr, :call) && expr.args[1] == :in && (expr.args[2] = string(expr.args[2])) + expr = (MacroTools.@capture(expr, y_ in z_)) ? :("$($y) in $($z isa Union{AbstractDict, AbstractVector} ? js_attr($z) : $z)") : :("$($expr)") + Expr(:kw, Symbol("v-for"), esc_expr(expr)) end const var"@for" = var"@recur" From 3e9bf4563f462c8c774e4b791b964b8bd16ee135 Mon Sep 17 00:00:00 2001 From: hhaensel Date: Tue, 31 Oct 2023 17:57:46 +0100 Subject: [PATCH 2/2] replace Base.isexpr for compatibility reasons --- src/Elements.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Elements.jl b/src/Elements.jl index 103071b6..ec9c204a 100644 --- a/src/Elements.jl +++ b/src/Elements.jl @@ -245,7 +245,7 @@ It is also possible to loop over `(v, k)` or `v`; index will always be zero-base """ macro recur(expr) - Base.isexpr(expr, :call) && expr.args[1] == :in && (expr.args[2] = string(expr.args[2])) + expr isa Expr && expr.head == :call && expr.args[1] == :in && (expr.args[2] = string(expr.args[2])) expr = (MacroTools.@capture(expr, y_ in z_)) ? :("$($y) in $($z isa Union{AbstractDict, AbstractVector} ? js_attr($z) : $z)") : :("$($expr)") Expr(:kw, Symbol("v-for"), esc_expr(expr))