DEV Community

Mbonu Blessing
Mbonu Blessing

Posted on

2 1

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

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.

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay