Build Your Own Web Framework in Elixir by Aditya Iyengar

Build Your Own Web Framework in Elixir by Aditya Iyengar

Author:Aditya Iyengar
Language: eng
Format: epub, pdf
Publisher: Packt Publishing Pvt Ltd
Published: 2023-05-18T00:00:00+00:00


Using EEx Smart Engine

EEx comes with the ability to override the engine that is being used to evaluate a template. The default engine used by EEx is EEx.SmartEngine. This module is built on top of the regular EEx.Engine but provides a way to speed up evaluation of a template by adding a special type of binding, assigns.

Let’s first take a look at an example:

./assigns.eex

<%= @a %> <%= @b %>

Now, let’s use the preceding template file to define a function in a module:

./module_b.ex

defmodule ModuleB do require EEx EEx.function_from_file(:def, :fun_b, "assigns.eex", [:assigns]) end

Updating our template and function to only take :assigns allows us to send different assigns without having to re-compile the template.

Now, let’s test out ModuleB.fun_b/1:

$ iex iex> Code.require_file("module_b.ex") [ {ModuleB, <<70, 79, 82, 49, 0, 0, 7, 68, 66, 69, 65, 77, 65, 116, 85, 56, 0, 0, 0,218, 0, 0, 0, 22, 14, 69, 108, 105, 120, 105, 114, 46, 77, 111, 100, 117, 108, 101, 66, 8, 95, 95, 105, 110, 102, 111, 95, ...>>} ] iex> ModuleB.fun_b(a: "Hello", b: "World") "Hello World
" iex> ModuleB.fun_b(a: "Hola", b: "World") "Hola World
"

This is super helpful to speed up the evaluation of templates while keeping the interface to use the templates simple and consistent. Phoenix uses a similar strategy to evaluate its templates.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.