Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expose functions to EEx templates

I am using EEx.eval_file and EEx.eval_string because I have no access to the templates during compile time and want to expose some functions that can be called from inside the templates.

What I could so it to pass a reference using the bindings (test: &test/1) but then I would have to call them like this which is not great from a user perspective: <%= test.("Hello") %>

Are there any other ways I could try?

like image 662
Phillipp Avatar asked Feb 01 '18 12:02

Phillipp


1 Answers

It's not documented AFAICS but EEx.eval_string internally calls Code.eval_quoted/3 and the third argument (options) is passed as is to that function. Code.eval_quoted/3 accepts a functions keyword argument in options which contains the functions to import:

:functions - a list of tuples where the first element is a module and the second a list of imported function names and arity; the list of function names and arity must be sorted

Source

Example:

iex(1)> EEx.eval_string ~s|<%= length("foo") %>|, [], functions: [{String, [length: 1]}]
"3"
like image 155
Dogbert Avatar answered Nov 08 '22 12:11

Dogbert