使用Nokogiri替换< img src />标记<%= image_tag%&gt ;? [英] Use Nokogiri to replace <img src /> tags with <%= image_tag %>?

查看:56
本文介绍了使用Nokogiri替换< img src />标记<%= image_tag%&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用nokogiri将所有img标签替换为图像标签?

How can I use nokogiri to replace all img tags with image tags? This is to utilize Rails' ability to plugin the correct asset server automatically?

require 'nokogiri'

class ToImageTag

  def self.convert
    Dir.glob("app/views/**/*").each do |filename|
      doc = Nokogiri::HTML(File.open(filename))
      doc.xpath("//img").each |img_tags|
        # grab the src and all the attributes and move them to ERB
      end

    # rewrite the file
    end

  rescue => err
    puts "Exception: #{err}"
  end

end


推荐答案

受到maerics响应的启发,我创建了一个脚本来执行此操作。 HTML实体没有问题,因为它仅使用nokogiri输出作为替换指南。实际的替换是通过使用String#gsub!

Somewhat inspired by maerics' response, I've created a script that does this. It doesn't have an issue with HTML entities because it only uses the nokogiri output as a guide for replacement. The actual replacement is done by using String#gsub!

https完成的://gist.github.com/1254319

这篇关于使用Nokogiri替换< img src />标记<%= image_tag%&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆