Role-Based Templates in Phoenix

Arun Karottu
Jul 30, 2017 · 2 min read

Building a simple reusable custom component to display HTML based on the role assigned to the logged in user

Our app at SMR has a lot templates that show some stuff to operators, more stuff to supervisors and even more stuff to admins. We found ourselves maintaining multiple copies of the same HTML pages and using them like so…

Definitely not ideal.

To simplify things, we decided to write a reusable component that allows us to keep our HTML in the same template and makes it easy to hide/show parts based on the role of the logged in user. Something like this…

restrict_by_role component in action

Setting it up

We setup a lib/my_app/web/components folder for our reusable components, borrowing the idea presented in this repo by Github user kimlindholm. In order to use these components, we included the following (screenshot from the repo) in our lib/my_app/web/web.ex .

lib/my_app/web/web.ex

Next we created a lib/my_app/web/components/component_helpers.ex file.

lib/my_app/web/components/component_helpers.ex

Creating the restrict_by_role component

Now to write the actual component for role-based templates. Create a lib/my_app/web/components/restrict_by_role/helpers.ex file.

lib/my_app/web/components/restrict_by_role/helpers.ex

Next create the view for the component at lib/my_app/web/components/restrict_by_role/view.ex .

lib/my_app/web/components/restrict_by_role/view.ex

Finally, write the template for the reusable component at lib/my_app/web/components/restrict_by_role/index.html.eex .

lib/my_app/web/components/restrict_by_role/index.html.eex

And that’s it

Now we’re able to use the restrict_by_role anywhere in our templates. And it has help us cut down on the number of html.eex files we have to maintain. In addition, it opens up the door for us to write other reusable components that make life easy for us.

Stay tuned for more posts about reusable components and other posts about Phoenix and Elixir

Thank you

The idea for this blog post comes from the following:

  1. This blog post by Daniel Berkompas
  2. This Github repo from user kimlindholm

Smart Metals Recycling

Arun Karottu

Written by

Full-Stack Developer at Smart Metals Recycling

Smart Metals Recycling

IT Asset Disposition company working with Elixir, Phoenix, Python, JavaScript etc. to save the environment

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade