Role-Based Templates in Phoenix
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…
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 .

Next we created a lib/my_app/web/components/component_helpers.ex file.
lib/my_app/web/components/component_helpers.exCreating 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.exNext 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.exFinally, 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.eexAnd 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:
- This blog post by Daniel Berkompas
- This Github repo from user kimlindholm

