module ECR
Overview
Embedded Crystal (ECR) is a template language for embedding Crystal code into other text, that includes but is not limited to HTML. The template is read and transformed at compile time and then embedded into the binary.
There are <%= %>
and <% %>
syntax. The former will render returned values.
The latter will not, but instead serve to control the structure as we do in Crystal.
Quick Example:
require "ecr/macros"
class Greeting
def initialize(@name)
end
ECR.def_to_s "greeting.ecr"
end
# greeting.ecr
Greeting, <%= @name %>!
Greeting.new("John").to_s
#=> Greeting, John!
Using logical statements:
# greeting.ecr
<% if @name %>
Greeting, <%= @name %>!
<% else %>
Greeting!
<% end %>
Greeting.new(nil).to_s
#=> Greeting!
Using loops:
require "ecr/macros"
class Greeting
def initialize(*names)
@names = names
end
ECR.def_to_s "greeting.ecr"
end
# greeting.ecr
<% @names.each do |name| %>
Hi, <%= name %>!
<% end %>
Greeting.new("John", "Zoe", "Ben").to_s
#=> Hi, John!
#=> Hi, Zoe!
#=> Hi, Ben!
Likewise, other Crystal logic can be implemented in ECR text.
Extended Modules
Defined in:
ecr/ecr.crecr/macros.cr
Constant Summary
-
DefaultBufferName =
"__str__"
Macro Summary
-
def_to_s(filename)
Defines a
to_s(io)
method whose body is the ECR contained in filename, translated to Crystal code. -
embed(filename, io_name)
Embeds an ECR file contained in filename into the program.
Macro Detail
Defines a to_s(io)
method whose body is the ECR contained
in filename, translated to Crystal code.
# greeting.ecr
Hello <%= @name %>!
require "ecr/macros"
class Greeting
def initialize(@name)
end
ECR.def_to_s "greeting.ecr"
end
Greeting.new("World").to_s # => "Hello World!"
The macro basically translates the text inside the given file to Crystal code that appends to the IO:
class Greeting
def to_s(io)
io << "Hello "
io << @name
io << "!"
end
end
Embeds an ECR file contained in filename into the program.
The generated code is the result of translating the contents of the ECR file to Crystal, a program that appends to the IO with the given io_name.
# greeting.ecr
Hello <%= name %>!
require "ecr/macros"
name = "World"
io = MemoryIO.new
ECR.embed "greeting.ecr", io
io.to_s # => "Hello World!"
The ECR.embed
line basically generates this:
io << "Hello "
io << name
io << "!"