htmlruby-on-railsjquery-mobilerelative-pathbase-tag

Overriding the base tag when reading in plain HTML


I am currently working on a jQM site with a Rails back end. A couple of the pages we use are reading in user uploaded HTML from AWS S3 and using the rails method 'html_safe' to render the html. This works great, but if the html has any references to files with relative path names they of course don't show up, since they would need to be grabbed from S3.

So what I am looking to do is to change the base tag so that these relative path names can acquire their assets. I have read the jQM docs on the Navmodel, but I am not to familiar with javascript and am not sure if I can use the *BaseURL methods to accomplish my goal or not.

Anybody have a possible solution? Any advice would be much appreciated. Thanks!


Solution

  • The <base> tag would work, but per the specification it applies to the whole page—which would break any other relative URLs on your page.

    If you don't want to make sure all of your other URLs are absolute the next best thing is probably to use Nokogiri to transform those URLs. E.g.

    require 'uri'
    require 'nokogiri'
    
    base_uri = URI 'http://example.com/'
    
    html = %{ <!DOCTYPE html>
              <html><body>
              <ul>
                <li><a href="/some_relative_url.html">Relative</a></li>
                <li><a href="http://stackoverflow.com/">Absolute</a></li>
                <li><img src="/a_relative_image.png" /></li>
              </ul>
              </body></html>
            }
    
    doc = Nokogiri::HTML html
    
    attrs = %w( @href @src )
    
    doc.search( *attrs ).each do |attr|
      path = URI attr
    
      attr.value = ( base_uri + path ).to_s unless path.absolute?
    end
    
    puts doc
    # => <!DOCTYPE html>
    #    <html><body>
    #    <ul>
    #      <li><a href="http://example.com/some_relative_url.html">Relative</a></li>
    #      <li><a href="http://stackoverflow.com/">Absolute</a></li>
    #      <li><img src="http://example.com/a_relative_image.png" /></li>
    #    </ul>
    #    </body></html>