JavaScript片段中的Ruby变量不能与Slim lang一起工作

Ruby variables in JavaScript snippet not working with Slim lang

本文关键字:Slim lang 一起 工作 不能 变量 片段 Ruby JavaScript      更新时间:2023-09-26

现在这已经让我撕了我的头发两个晚上-我在安装对讲机的JavaScript过程中。它要求在结束</body>标记之前放置一段代码,如下所示:

<script id="IntercomSettingsScriptTag">
window.intercomSettings = {
// TODO: The current logged in user's email address.
email: "john.doe@example.com",
// TODO: The current logged in user's sign-up date as a Unix timestamp.
created_at: 1234567890,
app_id: [redacted]
</script>

听起来很简单,但我的问题是,我需要使用一个Ruby变量来交换在当前登录用户的电子邮件地址到email字段-它应该只是一个简单的#{@user.full_name}(或者至少我认为它是,我只是一个初学者)。

然而,Slim阻止我这样做,因为它不执行变量,它只是在浏览器的源代码中原样打印整个代码片段。我认为这个问题类似于这个:如何在Slim模板内访问CoffeeScript引擎中的实例变量

下面是我的Slim代码:

|<script id="IntercomSettingsScriptTag">
 window.intercomSettings = {
 // TODO: The current logged in user's email address.
 email: "#{@user.email}",
 // TODO: The current logged in user's sign-up date as a Unix timestamp.
 created_at: #{@user.created_at.to_i},
 app_id: [redacted]
 };
 </script>

上面的代码使Slim崩溃,页面甚至无法加载。我也尝试在代码片段之前使用javascript: Slim函数声明变量,如上面的链接所示。没有运气。

有没有人对如何将变量传递到JavaScript有任何想法?如果你能给点指点我会很感激的。谢谢!

下面是有效的代码:

- if user_signed_in?
  script id="IntercomSettingsScriptTag"
    |
      window.intercomSettings = {
      // TODO: The current logged in user's full name
      name: "#{@current_user.full_name}",
      // TODO: The current logged in user's email address.
      email: "#{@current_user.email}",
      // TODO: The current logged in user's sign-up date as a Unix timestamp.
      created_at: #{@current_user.created_at.to_i},
      app_id: "eac384da45babdcac214d669601f1a29632f0d97"
      };

这可能会修复它

script id="IntercomSettingsScriptTag"
  |
    window.intercomSettings = {
      // TODO: The current logged in user's email address.
      email: "#{@user.email}",
      // TODO: The current logged in user's sign-up date as a Unix timestamp.
      created_at: #{@user.created_at.to_i},
      app_id: [redacted]
    };

是的,非常感谢你的提示!这是我最终成功的方法:

- if user_signed_in?
  script id="IntercomSettingsScriptTag"
    |
      window.intercomSettings = {
      // TODO: The current logged in user's full name
      name: "#{@current_user.full_name}",
      // TODO: The current logged in user's email address.
      email: "#{@current_user.email}",
      // TODO: The current logged in user's sign-up date as a Unix timestamp.
      created_at: #{@current_user.created_at.to_i},
      app_id: "eac384da45babdcac214d669601f1a29632f0d97"
      };

我只是一个初学者,所以看到它正常工作真的很令人兴奋。神奇的!