DEV Community

Mbonu Blessing
Mbonu Blessing

Posted on

How to render to different DOM structures in Rails based on view port

Hi,

I have a webpage that I want to render two different designs on based on if you are on a mobile device or laptop. I can easily use CSS to display or hide the classes but my main problem is that I have some datatables I am adding to the DOM but I need to target by ID. Here is what i have in my application.html.slim file

 body
    .ui.tab_desktop
      #left-column
        = render partial: 'layouts/sidebar'
      #right-column
        = render partial: 'layouts/header'
        = render 'layouts/flash'
        div id="context-#{controller_name}"
          = yield
        = render partial: 'layouts/footer'
    .ui.mobile
      = render partial: 'layouts/mobile_header'
      = render partial: 'layouts/mobile_sidebar'
      = render 'layouts/flash'
      div id="context-#{controller_name}"
        = yield
      = render partial: 'layouts/mobile_footer'
Enter fullscreen mode Exit fullscreen mode

Since we know that ID is supposed to be unique, the tables will only show on the desktop. Is there are better way to only render this part below once for both the mobile and desktop view?

div id="context-#{controller_name}"
        = yield
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
ben profile image
Ben Halpern

The answer might depend somewhat on your constraints in the project.

Are you allowed to tackle the issue on the server by asking if request.user_agent matches the correct devices?

Are you allowed to render the ID or even the whole section to the page with JavaScript on the client?

The scenario you've outlined here strikes me as less than ideal, so definitely knowing what tools you're allowed to use to solve it would be my first thought.