Thanks!
I actually meant __module__
– as that’s the point of the macro, to obtain a reference to the module where it’s invoked.
As for the reason, it’s quite complex. The simple code you propose at the end is what I have been using for a while, but doesn’t work entirely. It’s for an HTML based templating language.
There’s a module called Flax
which is part of an external package (Genie
) which can read an HTML template file with embedded Julia code. Flax
knows how to parse the HTML code and dynamically execute the Julia code in order to include parts of other views, add logic based of conditionals, loops, etc. Ultimately, it “executes” this code to generate the resulting HTML which is sent to the browser.
But these view files are defined and loaded into the user app, usually in a Controller module (or in some external Julia file). And Flax
needs access to the variables from the view file, which are defined in the user file (in the Controller). So Flax
evals the template in the Controller’s context, so the template code has access to the variables. It all works great with the exception of this @foreach
macro, which because is a macro, does not get evaled within the Controller’s scope but within Flax
itself.
Hence my need to grab __module__
(which is the Controller) and have the expression evaling in __module__
scope.
I hope that makes sense.
Example of a Flax template:
<table class="table table-striped">
<% @foreach(@vars(:translations)) do t %>
<tr>
<td style="width: 45%" id="original_$(t.id)" data-action="original">$(t.original |> escapeHTML)</td>
<td><button class="btn btn-outline-secondary btn-sm" title="Copy" data-action="copy">↪</button></td>
<td style="width: 45%" data-action="editor">
<textarea name="translation_$(t.id)" class="form-control">$( getfield(t, Symbol(@vars(:locale))) )</textarea>
</td>
<td><button class="btn btn-outline-secondary btn-sm" data-action="save">Save</button></td>
</tr>
<% end %>
</table>
This works well, but the problem is, if there is a variable x
defined outside the @foreach
inner block, it’s not accessible inside the block, as the code runs in a different scope.
I will give the nested code a try, thank you!