Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ECR.render for rendering without setting up an IO #6371

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions spec/std/ecr/ecr_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,8 @@ describe "ECR" do
ECR.embed "#{__DIR__}/../data/test_template6.ecr", io
io.to_s.should eq("string with -%")
end

it ".render" do
ECR.render("#{__DIR__}/../data/test_template2.ecr").should eq("123")
end
end
42 changes: 38 additions & 4 deletions src/ecr/macros.cr
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ module ECR
end
end

# Embeds an ECR file contained in *filename* into the program.
# Embeds an ECR file *filename* into the program and appends the content to
# an IO in the variable *io_name*.
#
# 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*.
# the ECR file to Crystal, a program that appends to an IO.
#
# ```text
# # greeting.ecr
Expand All @@ -59,7 +59,7 @@ module ECR
# io.to_s # => "Hello World!"
# ```
#
# The `ECR.embed` line basically generates this:
# The `ECR.embed` line basically generates this Crystal code:
#
# ```
# io << "Hello "
Expand All @@ -69,4 +69,38 @@ module ECR
macro embed(filename, io_name)
\{{ run("ecr/process", {{filename}}, {{io_name.id.stringify}}) }}
end

# Embeds an ECR file *filename* into the program and renders it to a string.
#
# The generated code is the result of translating the contents of
# the ECR file to Crystal, a program that appends to an IO and returns a string.
#
# ```text
# # greeting.ecr
# Hello <%= name %>!
# ```
#
# ```
# require "ecr/macros"
#
# name = "World"
#
# rendered = ECR.render "greeting.ecr"
# rendered # => "Hello World!"
# ```
#
# The `ECR.render` basically generates this Crystal code:
#
# ```
# String.build do |io|
# io << "Hello "
# io << name
# io << '!'
# end
# ```
macro render(filename)
::String.build do |%io|
::ECR.embed({{filename}}, %io)
end
end
end