-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
Copy pathcontroller.ex
1940 lines (1479 loc) · 60.1 KB
/
controller.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
defmodule Phoenix.Controller do
import Plug.Conn
alias Plug.Conn.AlreadySentError
require Logger
require Phoenix.Endpoint
@unsent [:unset, :set, :set_chunked, :set_file]
# View/Layout deprecation plan
# 1. Deprecate :namespace option in favor of :layouts on use
# 2. Deprecate setting a non-format view/layout on put_*
# 3. Deprecate rendering a view/layout from :_
@type view :: atom()
@type layout :: {module(), layout_name :: atom()} | atom() | false
@moduledoc """
Controllers are used to group common functionality in the same
(pluggable) module.
For example, the route:
get "/users/:id", MyAppWeb.UserController, :show
will invoke the `show/2` action in the `MyAppWeb.UserController`:
defmodule MyAppWeb.UserController do
use MyAppWeb, :controller
def show(conn, %{"id" => id}) do
user = Repo.get(User, id)
render(conn, :show, user: user)
end
end
An action is a regular function that receives the connection
and the request parameters as arguments. The connection is a
`Plug.Conn` struct, as specified by the Plug library.
Then we invoke `render/3`, passing the connection, the template
to render (typically named after the action), and the `user: user`
as assigns. We will explore all of those concepts next.
## Connection
A controller by default provides many convenience functions for
manipulating the connection, rendering templates, and more.
Those functions are imported from two modules:
* `Plug.Conn` - a collection of low-level functions to work with
the connection
* `Phoenix.Controller` - functions provided by Phoenix
to support rendering, and other Phoenix specific behaviour
If you want to have functions that manipulate the connection
without fully implementing the controller, you can import both
modules directly instead of `use Phoenix.Controller`.
## Rendering and layouts
One of the main features provided by controllers is the ability
to perform content negotiation and render templates based on
information sent by the client.
There are two ways to render content in a controller. One option
is to invoke format-specific functions, such as `html/2` and `json/2`.
However, most commonly controllers invoke custom modules called
views. Views are modules capable of rendering a custom format.
This is done by specifying the option `:formats` when defining
the controller:
use Phoenix.Controller,
formats: [:html, :json]
Now, when invoking `render/3`, a controller named `MyAppWeb.UserController`
will invoke `MyAppWeb.UserHTML` and `MyAppWeb.UserJSON` respectively
when rendering each format:
def show(conn, %{"id" => id}) do
user = Repo.get(User, id)
# Will invoke UserHTML.show(%{user: user}) for html requests
# Will invoke UserJSON.show(%{user: user}) for json requests
render(conn, :show, user: user)
end
Some formats are also handy to have layouts, which render content
shared across all pages. We can also specify layouts on `use`:
use Phoenix.Controller,
formats: [:html, :json],
layouts: [html: {MyAppWeb.Layouts, :app}]
You can also specify formats and layouts to render by calling
`put_view/2` and `put_layout/2` directly with a connection.
The line above can also be written directly in your actions as:
conn
|> put_view(html: MyAppWeb.UserHTML, json: MyAppWeb.UserJSON)
|> put_layout(html: MyAppWeb.Layouts)
### Backwards compatibility
In previous Phoenix versions, a controller you always render
`MyApp.UserView`. This behaviour can be explicitly retained by
passing a suffix to the formats options:
use Phoenix.Controller,
formats: [html: "View", json: "View"],
layouts: [html: MyAppWeb.Layouts]
### Options
When used, the controller supports the following options to customize
template rendering:
* `:formats` - the formats this controller will render
by default. For example, specifying `formats: [:html, :json]`
for a controller named `MyAppWeb.UserController` will
invoke `MyAppWeb.UserHTML` and `MyAppWeb.UserJSON` when
respectively rendering each format. If `:formats` is not
set, the default view is set to `MyAppWeb.UserView`
* `:layouts` - which layouts to render for each format,
for example: `[html: DemoWeb.Layouts]`. The value for each
format can be a tuple with the layout module and the layout name,
or just a module. When the name is omitted, the default layout
name `:app` is used.
Deprecated options:
* `:namespace` - sets the namespace for the layout. Use
`:layouts` instead
* `:put_default_views` - controls whether the default view
and layout should be set or not. Set `formats: []` and
`layouts: []` instead
## Plug pipeline
As with routers, controllers also have their own plug pipeline.
However, different from routers, controllers have a single pipeline:
defmodule MyAppWeb.UserController do
use MyAppWeb, :controller
plug :authenticate, usernames: ["jose", "eric", "sonny"]
def show(conn, params) do
# authenticated users only
end
defp authenticate(conn, options) do
if get_session(conn, :username) in options[:usernames] do
conn
else
conn |> redirect(to: "/") |> halt()
end
end
end
The `:authenticate` plug will be invoked before the action. If the
plug calls `Plug.Conn.halt/1` (which is by default imported into
controllers), it will halt the pipeline and won't invoke the action.
### Guards
`plug/2` in controllers supports guards, allowing a developer to configure
a plug to only run in some particular action.
plug :do_something when action in [:show, :edit]
Due to operator precedence in Elixir, if the second argument is a keyword list,
we need to wrap the keyword in `[...]` when using `when`:
plug :authenticate, [usernames: ["jose", "eric", "sonny"]] when action in [:show, :edit]
plug :authenticate, [usernames: ["admin"]] when not action in [:index]
The first plug will run only when action is show or edit. The second plug will
always run, except for the index action.
Those guards work like regular Elixir guards and the only variables accessible
in the guard are `conn`, the `action` as an atom and the `controller` as an
alias.
## Controllers are plugs
Like routers, controllers are plugs, but they are wired to dispatch
to a particular function which is called an action.
For example, the route:
get "/users/:id", UserController, :show
will invoke `UserController` as a plug:
UserController.call(conn, :show)
which will trigger the plug pipeline and which will eventually
invoke the inner action plug that dispatches to the `show/2`
function in `UserController`.
As controllers are plugs, they implement both [`init/1`](`c:Plug.init/1`) and
[`call/2`](`c:Plug.call/2`), and it also provides a function named `action/2`
which is responsible for dispatching the appropriate action
after the plug stack (and is also overridable).
### Overriding `action/2` for custom arguments
Phoenix injects an `action/2` plug in your controller which calls the
function matched from the router. By default, it passes the conn and params.
In some cases, overriding the `action/2` plug in your controller is a
useful way to inject arguments into your actions that you would otherwise
need to repeatedly fetch off the connection. For example, imagine if you
stored a `conn.assigns.current_user` in the connection and wanted quick
access to the user for every action in your controller:
def action(conn, _) do
args = [conn, conn.params, conn.assigns.current_user]
apply(__MODULE__, action_name(conn), args)
end
def index(conn, _params, user) do
videos = Repo.all(user_videos(user))
# ...
end
def delete(conn, %{"id" => id}, user) do
video = Repo.get!(user_videos(user), id)
# ...
end
"""
defmacro __using__(opts) do
opts =
if Macro.quoted_literal?(opts) do
Macro.prewalk(opts, &expand_alias(&1, __CALLER__))
else
opts
end
quote bind_quoted: [opts: opts] do
import Phoenix.Controller
import Plug.Conn
use Phoenix.Controller.Pipeline
if Keyword.get(opts, :put_default_views, true) do
plug :put_new_layout, Phoenix.Controller.__layout__(__MODULE__, opts)
plug :put_new_view, Phoenix.Controller.__view__(__MODULE__, opts)
end
end
end
defp expand_alias({:__aliases__, _, _} = alias, env),
do: Macro.expand(alias, %{env | function: {:action, 2}})
defp expand_alias(other, _env), do: other
@doc """
Registers the plug to call as a fallback to the controller action.
A fallback plug is useful to translate common domain data structures
into a valid `%Plug.Conn{}` response. If the controller action fails to
return a `%Plug.Conn{}`, the provided plug will be called and receive
the controller's `%Plug.Conn{}` as it was before the action was invoked
along with the value returned from the controller action.
## Examples
defmodule MyController do
use Phoenix.Controller
action_fallback MyFallbackController
def show(conn, %{"id" => id}, current_user) do
with {:ok, post} <- Blog.fetch_post(id),
:ok <- Authorizer.authorize(current_user, :view, post) do
render(conn, "show.json", post: post)
end
end
end
In the above example, `with` is used to match only a successful
post fetch, followed by valid authorization for the current user.
In the event either of those fail to match, `with` will not invoke
the render block and instead return the unmatched value. In this case,
imagine `Blog.fetch_post/2` returned `{:error, :not_found}` or
`Authorizer.authorize/3` returned `{:error, :unauthorized}`. For cases
where these data structures serve as return values across multiple
boundaries in our domain, a single fallback module can be used to
translate the value into a valid response. For example, you could
write the following fallback controller to handle the above values:
defmodule MyFallbackController do
use Phoenix.Controller
def call(conn, {:error, :not_found}) do
conn
|> put_status(:not_found)
|> put_view(MyErrorView)
|> render(:"404")
end
def call(conn, {:error, :unauthorized}) do
conn
|> put_status(:forbidden)
|> put_view(MyErrorView)
|> render(:"403")
end
end
"""
defmacro action_fallback(plug) do
Phoenix.Controller.Pipeline.__action_fallback__(plug, __CALLER__)
end
@doc """
Returns the action name as an atom, raises if unavailable.
"""
@spec action_name(Plug.Conn.t()) :: atom
def action_name(conn), do: conn.private.phoenix_action
@doc """
Returns the controller module as an atom, raises if unavailable.
"""
@spec controller_module(Plug.Conn.t()) :: atom
def controller_module(conn), do: conn.private.phoenix_controller
@doc """
Returns the router module as an atom, raises if unavailable.
"""
@spec router_module(Plug.Conn.t()) :: atom
def router_module(conn), do: conn.private.phoenix_router
@doc """
Returns the endpoint module as an atom, raises if unavailable.
"""
@spec endpoint_module(Plug.Conn.t()) :: atom
def endpoint_module(conn), do: conn.private.phoenix_endpoint
@doc """
Returns the template name rendered in the view as a string
(or nil if no template was rendered).
"""
@spec view_template(Plug.Conn.t()) :: binary | nil
def view_template(conn) do
conn.private[:phoenix_template]
end
@doc """
Sends JSON response.
It uses the configured `:json_library` under the `:phoenix`
application for `:json` to pick up the encoder module.
## Examples
iex> json(conn, %{id: 123})
"""
@spec json(Plug.Conn.t(), term) :: Plug.Conn.t()
def json(conn, data) do
response = Phoenix.json_library().encode_to_iodata!(data)
send_resp(conn, conn.status || 200, "application/json", response)
end
@doc """
A plug that may convert a JSON response into a JSONP one.
In case a JSON response is returned, it will be converted
to a JSONP as long as the callback field is present in
the query string. The callback field itself defaults to
"callback", but may be configured with the callback option.
In case there is no callback or the response is not encoded
in JSON format, it is a no-op.
Only alphanumeric characters and underscore are allowed in the
callback name. Otherwise an exception is raised.
## Examples
# Will convert JSON to JSONP if callback=someFunction is given
plug :allow_jsonp
# Will convert JSON to JSONP if cb=someFunction is given
plug :allow_jsonp, callback: "cb"
"""
@spec allow_jsonp(Plug.Conn.t(), Keyword.t()) :: Plug.Conn.t()
def allow_jsonp(conn, opts \\ []) do
callback = Keyword.get(opts, :callback, "callback")
case Map.fetch(conn.query_params, callback) do
:error ->
conn
{:ok, ""} ->
conn
{:ok, cb} ->
validate_jsonp_callback!(cb)
register_before_send(conn, fn conn ->
if json_response?(conn) do
conn
|> put_resp_header("content-type", "application/javascript")
|> resp(conn.status, jsonp_body(conn.resp_body, cb))
else
conn
end
end)
end
end
defp json_response?(conn) do
case get_resp_header(conn, "content-type") do
["application/json;" <> _] -> true
["application/json"] -> true
_ -> false
end
end
defp jsonp_body(data, callback) do
body =
data
|> IO.iodata_to_binary()
|> String.replace(<<0x2028::utf8>>, "\\u2028")
|> String.replace(<<0x2029::utf8>>, "\\u2029")
"/**/ typeof #{callback} === 'function' && #{callback}(#{body});"
end
defp validate_jsonp_callback!(<<h, t::binary>>)
when h in ?0..?9 or h in ?A..?Z or h in ?a..?z or h == ?_,
do: validate_jsonp_callback!(t)
defp validate_jsonp_callback!(<<>>), do: :ok
defp validate_jsonp_callback!(_),
do: raise(ArgumentError, "the JSONP callback name contains invalid characters")
@doc """
Sends text response.
## Examples
iex> text(conn, "hello")
iex> text(conn, :implements_to_string)
"""
@spec text(Plug.Conn.t(), String.Chars.t()) :: Plug.Conn.t()
def text(conn, data) do
send_resp(conn, conn.status || 200, "text/plain", to_string(data))
end
@doc """
Sends html response.
## Examples
iex> html(conn, "<html><head>...")
"""
@spec html(Plug.Conn.t(), iodata) :: Plug.Conn.t()
def html(conn, data) do
send_resp(conn, conn.status || 200, "text/html", data)
end
@doc """
Sends redirect response to the given url.
For security, `:to` only accepts paths. Use the `:external`
option to redirect to any URL.
The response will be sent with the status code defined within
the connection, via `Plug.Conn.put_status/2`. If no status
code is set, a 302 response is sent.
## Examples
iex> redirect(conn, to: "/login")
iex> redirect(conn, external: "https://elixir-lang.org")
"""
def redirect(conn, opts) when is_list(opts) do
url = url(opts)
html = Plug.HTML.html_escape(url)
body = "<html><body>You are being <a href=\"#{html}\">redirected</a>.</body></html>"
conn
|> put_resp_header("location", url)
|> send_resp(conn.status || 302, "text/html", body)
end
defp url(opts) do
cond do
to = opts[:to] -> validate_local_url(to)
external = opts[:external] -> external
true -> raise ArgumentError, "expected :to or :external option in redirect/2"
end
end
@invalid_local_url_chars ["\\", "/%09", "/\t"]
defp validate_local_url("//" <> _ = to), do: raise_invalid_url(to)
defp validate_local_url("/" <> _ = to) do
if String.contains?(to, @invalid_local_url_chars) do
raise ArgumentError, "unsafe characters detected for local redirect in URL #{inspect(to)}"
else
to
end
end
defp validate_local_url(to), do: raise_invalid_url(to)
@spec raise_invalid_url(term()) :: no_return()
defp raise_invalid_url(url) do
raise ArgumentError, "the :to option in redirect expects a path but was #{inspect(url)}"
end
@doc """
Stores the view for rendering.
Raises `Plug.Conn.AlreadySentError` if `conn` is already sent.
## Examples
# Use single view module
iex> put_view(conn, AppView)
# Use multiple view module for content negotiation
iex> put_view(conn, html: AppHTML, json: AppJSON)
"""
@spec put_view(Plug.Conn.t(), [{format :: atom, view}] | view) :: Plug.Conn.t()
def put_view(%Plug.Conn{state: state} = conn, formats) when state in @unsent do
put_private_view(conn, :phoenix_view, :replace, formats)
end
def put_view(%Plug.Conn{}, _module), do: raise(AlreadySentError)
defp put_private_view(conn, priv_key, kind, formats) when is_list(formats) do
formats = Enum.into(formats, %{}, fn {format, value} -> {to_string(format), value} end)
put_private_formats(conn, priv_key, kind, formats)
end
# TODO: Deprecate this whole branch
defp put_private_view(conn, priv_key, kind, value) do
put_private_formats(conn, priv_key, kind, %{_: value})
end
defp put_private_formats(conn, priv_key, kind, formats) when kind in [:new, :replace] do
update_in(conn.private, fn private ->
existing = private[priv_key] || %{}
new_formats =
case kind do
:new -> Map.merge(formats, existing)
:replace -> Map.merge(existing, formats)
end
Map.put(private, priv_key, new_formats)
end)
end
@doc """
Stores the view for rendering if one was not stored yet.
Raises `Plug.Conn.AlreadySentError` if `conn` is already sent.
"""
# TODO: Remove | layout from the spec once we deprecate put_new_view on controllers
@spec put_new_view(Plug.Conn.t(), [{format :: atom, view}] | view) :: Plug.Conn.t()
def put_new_view(%Plug.Conn{state: state} = conn, formats) when state in @unsent do
put_private_view(conn, :phoenix_view, :new, formats)
end
def put_new_view(%Plug.Conn{}, _module), do: raise(AlreadySentError)
@doc """
Retrieves the current view for the given format.
If no format is given, takes the current one from the connection.
"""
@spec view_module(Plug.Conn.t(), binary | nil) :: atom
def view_module(conn, format \\ nil) do
format = format || get_safe_format(conn)
# TODO: Deprecate if we fall on the first branch
# But we should only deprecate this after non-format is deprecated on put_*
case conn.private[:phoenix_view] do
%{_: value} when value != nil ->
value
%{^format => value} ->
value
formats ->
raise "no view was found for the format: #{inspect(format)}. " <>
"The supported formats are: #{inspect(Map.keys(formats || %{}) -- [:_])}"
end
end
@doc """
Stores the layout for rendering.
The layout must be given as keyword list where the key is the request
format the layout will be applied to (such as `:html`) and the value
is one of:
* `{module, layout}` with the `module` the layout is defined and
the name of the `layout` as an atom
* `layout` when the name of the layout. This requires a layout for
the given format in the shape of `{module, layout}` to be previously
given
* `false` which disables the layout
If `false` is given without a format, all layouts are disabled.
## Examples
iex> layout(conn)
false
iex> conn = put_layout(conn, html: {AppView, :application})
iex> layout(conn)
{AppView, :application}
iex> conn = put_layout(conn, html: :print)
iex> layout(conn)
{AppView, :print}
Raises `Plug.Conn.AlreadySentError` if `conn` is already sent.
"""
@spec put_layout(Plug.Conn.t(), [{format :: atom, layout}] | false) :: Plug.Conn.t()
def put_layout(%Plug.Conn{state: state} = conn, layout) do
if state in @unsent do
put_private_layout(conn, :phoenix_layout, :replace, layout)
else
raise AlreadySentError
end
end
defp put_private_layout(conn, private_key, kind, layouts) when is_list(layouts) do
formats =
Map.new(layouts, fn
{format, false} ->
{Atom.to_string(format), false}
{format, layout} when is_atom(layout) ->
format = Atom.to_string(format)
case conn.private[private_key] do
%{^format => {mod, _}} ->
{format, {mod, layout}}
%{} ->
raise "cannot use put_layout/2 or put_root_layout/2 with atom because " <>
"there is no previous layout set for format #{inspect(format)}"
end
{format, {mod, layout}} when is_atom(mod) and is_atom(layout) ->
{Atom.to_string(format), {mod, layout}}
{format, other} ->
raise ArgumentError, """
put_layout and put_root_layout expects an module and template per format, such as:
#{format}: {MyView, :app}
Got:
#{inspect(other)}
"""
end)
put_private_formats(conn, private_key, kind, formats)
end
defp put_private_layout(conn, private_key, kind, no_format) do
case no_format do
false ->
put_private_formats(conn, private_key, kind, %{_: false})
# TODO: Deprecate this branch
{mod, layout} when is_atom(mod) ->
put_private_formats(conn, private_key, kind, %{_: {mod, layout}})
# TODO: Deprecate this branch
layout when is_binary(layout) or is_atom(layout) ->
case Map.get(conn.private, private_key, %{_: false}) do
%{_: {mod, _}} ->
put_private_formats(conn, private_key, kind, %{_: {mod, layout}})
%{_: false} ->
raise "cannot use put_layout/2 or put_root_layout/2 with atom/binary when layout is false, use a tuple instead"
%{} ->
raise "you must pass the format when using put_layout/2 or put_root_layout/2 and a previous format was set, " <>
"such as: put_layout(conn, html: #{inspect(layout)})"
end
end
end
@doc """
Stores the layout for rendering if one was not stored yet.
See `put_layout/2` for more information.
Raises `Plug.Conn.AlreadySentError` if `conn` is already sent.
"""
# TODO: Remove | layout from the spec once we deprecate put_new_layout on controllers
@spec put_new_layout(Plug.Conn.t(), [{format :: atom, layout}] | layout) :: Plug.Conn.t()
def put_new_layout(%Plug.Conn{state: state} = conn, layout)
when (is_tuple(layout) and tuple_size(layout) == 2) or is_list(layout) or layout == false do
unless state in @unsent, do: raise(AlreadySentError)
put_private_layout(conn, :phoenix_layout, :new, layout)
end
@doc """
Stores the root layout for rendering.
The layout must be given as keyword list where the key is the request
format the layout will be applied to (such as `:html`) and the value
is one of:
* `{module, layout}` with the `module` the layout is defined and
the name of the `layout` as an atom
* `layout` when the name of the layout. This requires a layout for
the given format in the shape of `{module, layout}` to be previously
given
* `false` which disables the layout
## Examples
iex> root_layout(conn)
false
iex> conn = put_root_layout(conn, html: {AppView, :root})
iex> root_layout(conn)
{AppView, :root}
iex> conn = put_root_layout(conn, html: :bare)
iex> root_layout(conn)
{AppView, :bare}
Raises `Plug.Conn.AlreadySentError` if `conn` is already sent.
"""
@spec put_root_layout(Plug.Conn.t(), [{format :: atom, layout}] | false) ::
Plug.Conn.t()
def put_root_layout(%Plug.Conn{state: state} = conn, layout) do
if state in @unsent do
put_private_layout(conn, :phoenix_root_layout, :replace, layout)
else
raise AlreadySentError
end
end
@doc """
Sets which formats have a layout when rendering.
## Examples
iex> layout_formats(conn)
["html"]
iex> put_layout_formats(conn, ["html", "mobile"])
iex> layout_formats(conn)
["html", "mobile"]
Raises `Plug.Conn.AlreadySentError` if `conn` is already sent.
"""
@deprecated "put_layout_formats/2 is deprecated, pass a keyword list to put_layout/put_root_layout instead"
@spec put_layout_formats(Plug.Conn.t(), [String.t()]) :: Plug.Conn.t()
def put_layout_formats(%Plug.Conn{state: state} = conn, formats)
when state in @unsent and is_list(formats) do
put_private(conn, :phoenix_layout_formats, formats)
end
def put_layout_formats(%Plug.Conn{}, _formats), do: raise(AlreadySentError)
@doc """
Retrieves current layout formats.
"""
@spec layout_formats(Plug.Conn.t()) :: [String.t()]
@deprecated "layout_formats/1 is deprecated, pass a keyword list to put_layout/put_root_layout instead"
def layout_formats(conn) do
Map.get(conn.private, :phoenix_layout_formats, ~w(html))
end
@doc """
Retrieves the current layout for the given format.
If no format is given, takes the current one from the connection.
"""
@spec layout(Plug.Conn.t(), binary | nil) :: {atom, String.t() | atom} | false
def layout(conn, format \\ nil) do
get_private_layout(conn, :phoenix_layout, format)
end
@doc """
Retrieves the current root layout for the given format.
If no format is given, takes the current one from the connection.
"""
@spec root_layout(Plug.Conn.t(), binary | nil) :: {atom, String.t() | atom} | false
def root_layout(conn, format \\ nil) do
get_private_layout(conn, :phoenix_root_layout, format)
end
defp get_private_layout(conn, priv_key, format) do
format = format || get_safe_format(conn)
case conn.private[priv_key] do
%{_: value} -> if format in [nil | layout_formats(conn)], do: value, else: false
%{^format => value} -> value
_ -> false
end
end
@doc """
Render the given template or the default template
specified by the current action with the given assigns.
See `render/3` for more information.
"""
@spec render(Plug.Conn.t(), Keyword.t() | map | binary | atom) :: Plug.Conn.t()
def render(conn, template_or_assigns \\ [])
def render(conn, template) when is_binary(template) or is_atom(template) do
render(conn, template, [])
end
def render(conn, assigns) do
render(conn, action_name(conn), assigns)
end
@doc """
Renders the given `template` and `assigns` based on the `conn` information.
Once the template is rendered, the template format is set as the response
content type (for example, an HTML template will set "text/html" as response
content type) and the data is sent to the client with default status of 200.
## Arguments
* `conn` - the `Plug.Conn` struct
* `template` - which may be an atom or a string. If an atom, like `:index`,
it will render a template with the same format as the one returned by
`get_format/1`. For example, for an HTML request, it will render
the "index.html" template. If the template is a string, it must contain
the extension too, like "index.json"
* `assigns` - a dictionary with the assigns to be used in the view. Those
assigns are merged and have higher precedence than the connection assigns
(`conn.assigns`)
## Examples
defmodule MyAppWeb.UserController do
use Phoenix.Controller
def show(conn, _params) do
render(conn, "show.html", message: "Hello")
end
end
The example above renders a template "show.html" from the `MyAppWeb.UserView`
and sets the response content type to "text/html".
In many cases, you may want the template format to be set dynamically based
on the request. To do so, you can pass the template name as an atom (without
the extension):
def show(conn, _params) do
render(conn, :show, message: "Hello")
end
In order for the example above to work, we need to do content negotiation with
the accepts plug before rendering. You can do so by adding the following to your
pipeline (in the router):
plug :accepts, ["html"]
## Views
By default, Controllers render templates in a view with a similar name to the
controller. For example, `MyAppWeb.UserController` will render templates inside
the `MyAppWeb.UserView`. This information can be changed any time by using the
`put_view/2` function:
def show(conn, _params) do
conn
|> put_view(MyAppWeb.SpecialView)
|> render(:show, message: "Hello")
end
`put_view/2` can also be used as a plug:
defmodule MyAppWeb.UserController do
use Phoenix.Controller
plug :put_view, html: MyAppWeb.SpecialView
def show(conn, _params) do
render(conn, :show, message: "Hello")
end
end
## Layouts
Templates are often rendered inside layouts. By default, Phoenix
will render layouts for html requests. For example:
defmodule MyAppWeb.UserController do
use Phoenix.Controller
def show(conn, _params) do
render(conn, "show.html", message: "Hello")
end
end
will render the "show.html" template inside an "app.html"
template specified in `MyAppWeb.LayoutView`. `put_layout/2` can be used
to change the layout, similar to how `put_view/2` can be used to change
the view.
"""
@spec render(Plug.Conn.t(), binary | atom, Keyword.t() | map) :: Plug.Conn.t()
def render(conn, template, assigns)
when is_atom(template) and (is_map(assigns) or is_list(assigns)) do
format =
get_format(conn) ||
raise "cannot render template #{inspect(template)} because conn.params[\"_format\"] is not set. " <>
"Please set `plug :accepts, ~w(html json ...)` in your pipeline."
render_and_send(conn, format, Atom.to_string(template), assigns)
end
def render(conn, template, assigns)
when is_binary(template) and (is_map(assigns) or is_list(assigns)) do
{base, format} = split_template(template)
conn |> put_format(format) |> render_and_send(format, base, assigns)
end
def render(conn, view, template)
when is_atom(view) and (is_binary(template) or is_atom(template)) do
IO.warn(
"#{__MODULE__}.render/3 with a view is deprecated, see the documentation for render/3 for an alternative"
)
render(conn, view, template, [])
end
@doc false
@deprecated "render/4 is deprecated. Use put_view + render/3"
def render(conn, view, template, assigns)
when is_atom(view) and (is_binary(template) or is_atom(template)) do
conn
|> put_view(view)
|> render(template, assigns)
end
defp render_and_send(conn, format, template, assigns) do
view = view_module(conn, format)
conn = prepare_assigns(conn, assigns, template, format)
data = render_with_layouts(conn, view, template, format)
conn
|> ensure_resp_content_type(MIME.type(format))
|> send_resp(conn.status || 200, data)
end
defp render_with_layouts(conn, view, template, format) do
render_assigns = Map.put(conn.assigns, :conn, conn)
case root_layout(conn, format) do
{layout_mod, layout_tpl} ->
{layout_base, _} = split_template(layout_tpl)
inner = template_render(view, template, format, render_assigns)
root_assigns = render_assigns |> Map.put(:inner_content, inner) |> Map.delete(:layout)
template_render_to_iodata(layout_mod, layout_base, format, root_assigns)
false ->
template_render_to_iodata(view, template, format, render_assigns)
end
end
defp template_render(view, template, format, assigns) do
metadata = %{view: view, template: template, format: format}