简体   繁体   English

将文本文件内容加载到Rails的JavaScript中

[英]Load text file contents into JavaScript in Rails

I have an SVG file that I want to dynamically load, inline, via JavaScript in my Rails application. 我有一个要通过Rails应用程序中的JavaScript动态加载,内联的SVG文件。 I need to load the SVG inline so that I can apply a CSS fill property to it. 我需要加载SVG内联,以便可以对其应用CSS fill属性。

I'd rather not load the SVG file via AJAX to avoid potential lag before the SVG is visible. 我宁愿不通过AJAX加载SVG文件,以避免在看到SVG之前可能出现的延迟。

Ideally what I'd like to do is to tell Rails that, in my app/assets/icons/ directory, I have icons calendar.svg and phone.svg , and that Rails (Sprockets?) should take the contents of those SVG files and set them as string values in a JavaScript object SVG , so that I may access them in my JavaScript code like this: 理想情况下,我想告诉Rails在我的app/assets/icons/目录中,有icon calendar.svgphone.svg图标,并且Rails(Sprockets?)应该使用那些SVG文件的内容。并将它们设置为JavaScript对象SVG中的字符串值,这样我就可以在JavaScript代码中访问它们,如下所示:

var view = {
  render: function () {
    this.element.innerHTML = SVG['app/assets/icons/calendar.svg'];
  }
};

Preferably, the solution is generalized to more than just SVGs, and I could potentially load any data in text format via JS, eg TEXT['app/assets/icons/calendar.svg'] or even TEXT['app/assets/etc/some-text-file.text'] . 最好将解决方案推广到不仅仅是SVG,而且我有可能通过JS加载文本格式的任何数据,例如TEXT['app/assets/icons/calendar.svg']甚至是TEXT['app/assets/etc/some-text-file.text']

Is there any way to do this in Rails? 在Rails中有什么方法可以做到这一点吗?

We ended up writing a sprockets transformer for this: https://github.com/cloversites/js-text-rails 我们最终为此编写了链轮转换器: https : //github.com/cloversites/js-text-rails

$ bundle install js-text-rails

require your files, eg in app/assets/javascripts/application.js: 需要您的文件,例如在app/assets/javascripts/application.js:

//= require_tree ../images/icons

Where app/assets/images/icons contains the file envelope.svg . 其中app/assets/images/icons包含文件envelope.svg

Anywhere in your application's JavaScript code, access the text file contents via the global SVG variable: 在应用程序的JavaScript代码中的任何位置,都可以通过全局SVG变量访问文本文件的内容:

var envelopeIcon = SVG['icons/envelope'];
// Do something with `envelopeIcon`...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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