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

Implement .render_subject/2 and .render_subject/3 #15

Closed
sitch opened this issue Nov 15, 2017 · 3 comments
Closed

Implement .render_subject/2 and .render_subject/3 #15

sitch opened this issue Nov 15, 2017 · 3 comments

Comments

@sitch
Copy link

sitch commented Nov 15, 2017

For Example:

.render_subject/2

Renders a phoenix template from previous assigns

iex> new(assigns: %{name: "Sitch"})
     |> render_subject("welcome.html") # contains `Welcome, <%= @name %>!`

%{assigns: %{name: "Sitch"}, subject: "Welcome, Sitch!"}

Renders a ~S sigil from previous assigns

iex> new(assigns: %{name: "Sitch"})
     |> render_subject(~S(Welcome, <%= @name %>!)))

%{assigns: %{name: "Sitch"}, subject: "Welcome, Sitch!"}

.render_subject/3

Renders a phoenix template with merged assigns

iex> new()
     |> render_subject("welcome.html", name: "Sitch") # contains `Welcome, <%= @name %>!`

%{assigns: %{name: "Sitch"}, subject: "Welcome, Sitch!"}

Renders a ~S sigil with with merged assigns

iex> new()
     |> render_subject(~S(Welcome, <%= @name %>!), %{name: "Sitch"})

%{assigns: %{name: "Sitch"}, subject: "Welcome, Sitch!"}
@stevedomin
Copy link
Member

Hello @sitch.

Thanks for opening an issue!

Would you mind sharing more details about your use-case? I'm struggling to see where this would be more powerful than a simple string interpolation?

Thanks!

@sitch
Copy link
Author

sitch commented Nov 15, 2017

Well firstly, rendering the subject as a template can be useful non-devs to maintain the templates. My use case is more that i am passing an assigns map to render_body/3 or to Swoosh.Email.new/1, and I can just repeat myself or i can access those assigns variables for consistency

@sitch
Copy link
Author

sitch commented Nov 15, 2017

This is what i'm using internally to do:

new()
|> assign(:name, "Sitch")
|> render_subject(~S("Welcome #{name}"))
|> render_body("template.html")
defmodule RenderingSubject do

  def render_subject(%Swoosh.Email{assigns: assigns} = struct, template) do
    subject = eval_quoted_string(template, assigns)
    %{struct | subject: subject}
  end

  def eval_quoted_string(template, assigns) when is_binary(template) and is_map(assigns) do
    with assignment_list <- Enum.into(assigns, []),
         {result, _assign} <- Code.eval_string(template, assignment_list)
    do
      result
    else
      _ -> raise "Unknown argument in .eval_quoted_string/2"
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants