1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 23:28:02 +00:00

Add Render A Template To A String as a phoenix til

This commit is contained in:
jbranchaud
2016-09-10 20:08:33 -05:00
parent c6e6353208
commit e3789fc764
2 changed files with 30 additions and 1 deletions

View File

@@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really
warrant a full blog post. These are mostly things I learn by pairing with
smart people at [Hashrocket](http://hashrocket.com/).
_467 TILs and counting..._
_468 TILs and counting..._
---
@@ -24,6 +24,7 @@ _467 TILs and counting..._
* [JavaScript](#javascript)
* [Linux](#linux)
* [Mac](#mac)
* [Phoenix](#phoenix)
* [PostgreSQL](#postgresql)
* [Rails](#rails)
* [Ruby](#ruby)
@@ -188,6 +189,10 @@ _467 TILs and counting..._
- [List All The Say Voices](mac/list-all-the-say-voices.md)
- [Resizing Both Corners Of A Window](mac/resizing-both-corners-of-a-window.md)
### Phoenix
- [Render A Template To A String](phoenix/render-a-template-to-a-string.md)
### PostgreSQL
- [A Better Null Display Character](postgres/a-better-null-display-character.md)

View File

@@ -0,0 +1,24 @@
# Render A Template To A String
Templates in a Phoenix application ultimately get compiled to functions that
can be quickly rendered with the necessary data. We can take a look at how a
template will be rendered using
[`Phoenix.View.render_to_string/3`](https://hexdocs.pm/phoenix/Phoenix.View.html#render_to_string/3).
First, we need a template:
```elixir
# user.html.eex
<h1><%= @user.first_name %></h1>
<h5><%= @user.username %> (<%= @user.email %>)</h5>
```
We can then render that template for the view with some user:
```elixir
> user = %User{first_name: "Liz", last_name: "Lemon", username: "llemon", email: "lizlemon@nbc.com"}
%MyApp.User{...}
> Phoenix.View.Render_to_string(MyApp.UserView, "user.html", user: user)
"<h1>Liz</h1>\n<h5>llemon (lizlemon@nbc.com)</h5>\n"
```