inhji
Hi there,
I have a controller with an action that renders some html. Now I want to extend that action to render some json when the content type is application/json*
I was hoping I could use pattern matching to achieve this, but this does not work (the html action always gets executed):
def index(%{req_headers: [{"content-type", "application/json"}]} = conn, _params) do
json(conn, %{some: "response"})
end
def index(conn, _params) do
render(conn, "index.html")
end
This does work:
def index(conn, _params) do
headers = Enum.into(conn.req_headers, %{})
if headers["content-type"] == "application/json" do
json(conn, %{some: "response"})
else
render(conn, "index.html")
end
end
Is there a cleaner to achieve this?
Thanks!
Trending in Questions
Hello!
Suppose you are building workflow (order / task / payment) processing system with the following requirements:
Each workflow con...
New
I’m aware of 2 such projects, are there others?
git: GitHub - team-alembic/realworld: A fullstack Phoenix LiveView application with back...
New
Hi everyone.
My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
Hello folks!
So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
How Can I Optimise Compile Time Dependencies
I have been building an elixir application for about 2 years now. Many modules and files ha...
New
Hi,
we run different LLM models across a cluster, with each node loading a configurable subset. Model-specific queues let nodes consume ...
New
Other Trending Topics
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself.
My main conc...
New
I love Elixir. It’s one of 2 programming languages I’ve ever fallen in love with.
But I don’t use it anymore.
Serverless was the promis...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #ai
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixirconf-us
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #elixirconf-eu
- #api
- #forms
- #security
- #hex










Showing Posts 1 to 5- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
voltone
The “Content-Type” header describes the payload of the client’s request. The response format is normally negotiated based on the client’s “Accept” header and the server’s capabilities.
See:
In a standard Phoenix application you should already have something like
plug :accepts, ["html"]in one of your router’s pipelines. You can update it to["html", "json"], make sure your client sends the correct “Accept” header and checkget_format(conn)when choosing what to render.BTW, the reason pattern matching does not work is because it will only match a list where the only element is
{"content-type", "application/json"}, which is never the case.NobbZ
indexis usally called on aGETrequest, and setting acontent-typeheader does not make much sense there.Besides of that, you match on a list that has exactly one element. This is unlikely to be true for any list of headers.
Also I’m seconding @voltone, that you probably want to check for the
"accept"header instead and leverageplugs that are already available.AlchemistCamp
Another option you have is to define a render function for both an
index.htmland anindex.jsonand then just pass the action’s atom to the render function in your controller. In other words instead of havingrender(conn, "index.html"...), you’ll haverender(conn, :index...). Here’s an example from one of my apps:card_controller.ex:
With this in place, Phoenix will look for the appropriate (view) render function or template for each content type. You could have an
index.html.eex, anindex.json.eex, anindex.xml.eexand even more options all in the same template directory.What I often do with JSON is just define a render function directly in the view instead of making a template, since it’s so short and Phoenix will automatically use Jason (or whichever encoder you’ve configured) to encode your data properly.
card_view.ex:
As @voltone pointed out, you’ll need to make sure your router plug accepts includes JSON and then Phoenix will honor the Accept header coming from the front end.
Using axios (or Vue.axios in my case), you can do that with the headers field like this:
kokolegorille
Maybe this post can help too. It allows to use suffix for routes.
inhji
Thank you everybody for your answers!
I tried two approaches:
The first one involved a plug that called
get_formatand put its output to theprivatemap. This lets me pattern match on the format like i originally imagined:The approach as outlined by @AlchemistCamp ended up being more appealing to me because all I had to do was adding the json
renderfunction to the view and changing the render function in the controller: