如何将环境变量嵌入到 Rails 中的 .coffee 文件中



我看到了这个问题,但它不起作用:如何从javascript上的rails访问环境变量?

我有这个代码

subscriptions.coffee.erb
$ ->
  # Create a Stripe client
  stripe = Stripe( "<% ENV['STRIPE_PUBLIC'] %>" )

我设置了这个环境

C:UsersChloeworkspace>echo %STRIPE_PUBLIC%
pk_test_7aMtxxxxxxxxxxxxx4p3M
C:UsersChloeworkspace>rails server --bind 0.0.0.0
=> Booting Puma

然而,它正在生成此 JS:

http://localhost:3000/assets/subscriptions.self-dfceb50c7f2eec8201fd3f59a7660a6763333b1e27f564e812f93c8ce9019188.js?body=1
(function() {
  $(function() {
    var card, elements, form, stripe, stripeTokenHandler, style;
    stripe = Stripe("");

在模板中,缺少实际呈现 ERB 表达式输出的=。以下方法应该有效:

stripe = Stripe("<%= ENV['STRIPE_PUBLIC'] %>")

有关详细信息,请参阅文档。

没有人对我有答案,我不能等一整天,所以我用不同的方式做了。

_form.haml
=javascript_include_tag 'https://js.stripe.com/v3/'
:javascript
  window.stripe_public = "#{ENV['STRIPE_PUBLIC']}";
subscriptions.coffee
$ ->
  # Create a Stripe client
  stripe = Stripe( window.stripe_public )

收益 率

view-source:http://localhost:3000/users/1/subscriptions/new
  <script src="https://js.stripe.com/v3/"></script>
  <script>
    window.stripe_public = "pk_test_7xxxxxxxxxxxx4p3M";
  </script>
http://localhost:3000/assets/subscriptions.self-dfceb50c7f2eec8201fd3f59a7660a6763333b1e27f564e812f93c8ce9019188.js?body=1
(function() {
  $(function() {
    var card, elements, form, stripe, stripeTokenHandler, style;
    stripe = Stripe(window.stripe_public);

最新更新