带有turbolinks的Rails 4,嵌入式gists不起作用

时间:2013-11-06 23:22:37

标签: ruby-on-rails github pjax gist turbolinks

当试图嵌入一个要点,然后通过turbolinks访问一个页面时,它只是空的,没有任何显示。

当使用完全重新加载访问同一页面时,它可以正常工作。

有关如何使其发挥作用的任何想法?

2 个答案:

答案 0 :(得分:1)

制作一个新文件,例如gist.js.coffee,并在其中添加以下咖啡脚本

$ ->
  loadGists()
  $(document).on 'page:load', loadGists

loadGists = ->
  $('.gist').each ->
    loadGist $(this)

loadGist = ($gist) ->
  callbackName = 'c' + Math.random().toString(36).substring(7)

  window[callbackName] = (gistData) ->
    delete window[callbackName]
    html = '<link rel="stylesheet" href="' + encodeURI(gistData.stylesheet) + '"></link>'
    html += gistData.div
    $gist.html html
    script.parentNode.removeChild script

  script = document.createElement 'script'
  script.setAttribute 'src', [
    $gist.data('src'), 
    $.param(
      callback: callbackName
      file: $gist.data('file') || ''
    )
  ].join '?'
  document.body.appendChild script

接下来,将所有gist脚本标记更改为具有gist类的div以及URL和文件名的数据属性。另外,使用.json扩展名而不是.js。

<!-- before -->
<script src="https://gist.github.com/username/gist_id.js"></script>
<script src="https://gist.github.com/username/gist_id.js?file=file_name"></script>

<!-- after -->
<div class="gist" data-src="https://gist.github.com/username/gist_id.json"></div>
<div class="gist" data-src="https://gist.github.com/username/gist_id.json" data-file="file_name"></div>

那应该可以解决你的问题。请参阅我撰写的关于using github embedded gists with turbolinks

的完整教程

答案 1 :(得分:0)

来自Turbolinks的文档:

  

Turbolinks会评估它访问过的网页中的所有脚本标记   标签没有类型或类型是text / javascript。所有其他   脚本标签将被忽略。

因此,通过将<script src="gist.github.com/foobar/123.js"></script>放入您返回的html中,turbolinks会尝试对其进行评估,而不是仅显示其内容。 尝试将其与其他链接嵌入(https://gist.github.com/xxx/yyyyy