Parsing user agent - creating dynamic form

I would like to use a different layout and template depending if the user uses PC or a smartphone.
So, I would like to switch layout and template by checking user agent.
What is the best way to check user agent and switch layout and template without using library?

I was thinking having a list and then filtering it for Mobile user agents… but seems hacky and bad practice.

Where there is no other choice I have used the Device Atlas database. But your concerns are reasonable: They have over 21,000 agent strings in their database!

I believe it is vastly better to understand the browser capabilities over trying to do user agent detection. The best alternative would be responsive templates. Or as a last resort some small JS to transmit screen dimensions (for example), but the experience is much better for the end user.

Also many css frameworks are responsive and adapt layout to media breakpoint.

I also believe that CSS can handle most of your intentions, but you can enhance with: ua_parser or us_inspector. Maybe even cache most common.