diff --git a/src/Elements.jl b/src/Elements.jl index 6f69ed05..ec9c204a 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) + 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)) end const var"@for" = var"@recur"