简体   繁体   中英

Passing rails variables to javascript lightbox popup

I would need to pass rails variables related to a certain clicked image into its lightbox container.

I'm outputting all of the media uploads into my _content.html.erb layout like this

<% @media_uploads.each do |media_upload| %>
<%= media_upload.title %>
<%= media_upload.user.username unless media_upload.user.nil? %>
<%= media_upload.description %>

And I'm initializing magnific popup from my application.js when any image is clicked like this

$('.box p a').magnificPopup({
  type:'image',
  image: {
    markup: '<div class="mfp-figure">'+'<div class="mfp-close"></div>'+
    '<div class="mfp-box-top">//username, title?</div>'+
    '<div class="mfp-img">//this is where the picture is rendered</div>'+
    '<div class="mfp-box-bottom">//description?</div>'+
    '</div>'+'</div>', 
  }
});

Any ideas how to pass the variables from rails to magnific markup? I would like to have appropriate user, title and description (among other things) displayed inside the corresponding popup - inside mfp-box-top and mfp-box-bottom divs.

Thank you for any tips or tricks!

You have to solve this on the client. The easiest way would be to just render this information additionally as 'data-' attributes on the link or some other html element like this:

 <a href='nice.img' data-title='nice', data-user-name='chuck', data-descrption='lorem impsum' />

Then query for this info in generic way within the maginific initialiser.

    $('.box p a').magnificPopup({
    type:'image',
    image: {
      markup: ...
      '<div class="mfp-box-top">' + $(this).attr('data-title') + '</div>'
      ...
      }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM