Skip to content

Commit

Permalink
Adding the ability to use a layout for your html templates. (#70)
Browse files Browse the repository at this point in the history
* Adding the ability to use a layout for your html templates. Fixes #69

* apparently I can't do a comment here...
  • Loading branch information
jwoertink authored Jul 14, 2022
1 parent 7643fc4 commit a77ff3c
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 3 deletions.
11 changes: 11 additions & 0 deletions spec/email_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,11 @@ private class EmailWithCustomAttributes < Carbon::Email
end
end

private class EmailWithLayout < BareMinimumEmail
templates html
layout custom_layout
end

describe Carbon::Email do
it "can build a bare minimum email" do
email = BareMinimumEmail.new
Expand Down Expand Up @@ -135,4 +140,10 @@ describe Carbon::Email do

it "normalizes recipients" do
end

it "includes a layout" do
email = EmailWithLayout.new
email.html_body.should contain "Email Layout"
email.html_body.should contain "Email body"
end
end
3 changes: 3 additions & 0 deletions spec/templates/custom_layout/layout.ecr
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<h1>Email Layout</h1>

<%= content %>
1 change: 1 addition & 0 deletions spec/templates/email_with_layout/html.ecr
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<p>Email body</p>
25 changes: 22 additions & 3 deletions src/carbon/email.cr
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,39 @@ abstract class Carbon::Email

def text_body; end

def text_layout(content_io : IO); end

def html_body; end

def html_layout(content_io : IO); end

getter headers

macro inherited
macro templates(*content_types)
\{% for content_type in content_types %}
def \{{ content_type }}_body : String
io = IO::Memory.new
ECR.embed "#{__DIR__}/templates/\{{ @type.name.underscore.gsub(/::/, "_") }}/\{{ content_type }}.ecr", io
io.to_s
content_io = IO::Memory.new
ECR.embed "#{__DIR__}/templates/\{{ @type.name.underscore.gsub(/::/, "_") }}/\{{ content_type }}.ecr", content_io
\{{ content_type }}_layout(content_io) || content_io.to_s
end
\{% end %}
end

# Specify an HTML template layout
#
# ```
# templates html
# layout email_layout
# ```
macro layout(template_name)
def html_layout(content_io : IO)
content = content_io.to_s
layout_io = IO::Memory.new
ECR.embed "#{__DIR__}/templates/\{{ template_name.id }}/layout.ecr", layout_io
layout_io.to_s
end
end
end

@headers = {} of String => String
Expand Down

0 comments on commit a77ff3c

Please sign in to comment.