【问题标题】:Embedding Youtube Videos in Phoenix EEX templates在 Phoenix EEX 模板中嵌入 Youtube 视频
【发布时间】:2026-01-09 02:35:02
【问题描述】:

我写了如下代码来展示项目:

<%= for project <- @projects do %>
<div class="col-sm-4">
 <div class="panel panel-default"  style="min-height: 1200px; margin-bottom:50px;height:auto;">
    <div class="panel-heading">
        <img src="<%= Microflow.Avatar.url({project.picture, project}, :original) %>" alt="" width="330px" height="240px"/>

      </div>
    <div class="panel-body" style="min-height: 350px">
      <h2 style="font-family: 'Montserrat', sans-serif;"><%= project.name %></h2>
      <h3 style="font-family: 'Raleway', sans-serif;"><%= raw(project.description) %></h3>
      <h2 style="font-family: 'Montserrat', sans-serif;">

      </h2>
      <h2 style="font-family: 'Montserrat', sans-serif;"><%= project.raise_amount %> USD</h2>
    <iframe width="100%" height="100%" src= "<%=project.video_url%>"</iframe>  
<%= link "Delete Project", to: project_path(@conn, :delete, project), method: :delete, data: [confirm: "Are you sure?"], class: "btn btn-info btn-xs" %>
<%= link "Start Your Own Project", to: project_path(@conn, :new), method: :new, class: "btn btn-success btn-xs" %>
          </div>
           </div>
             </div>
<% end %>

除了这一行之外,一切都很好:

<iframe width="100%" height="100%" src= "<%=project.video_url%>"</iframe>

其中显示:

"No route found for GET /Video%20Goes%20Here (MyApp.Router)"

我需要修复路由或定义函数吗?...以下 Ruby 指南在 Phoenix/Elixir 中可能仍然有效,但需要进行一些调整:

How to add youtube frame to ERB file Embed youtube video in rails

【问题讨论】:

    标签: iframe youtube elixir phoenix-framework


    【解决方案1】:

    看起来您可能正在使用视频 URL 的相对路径。这意味着它将相对于您当前的 URL 进行投放。

    例如,如果您在http://example.com/projects/1 上并且project.video_url/some_video_url,那么 iframe 将使用`http://example.com/some_video_url

    如果您尝试嵌入 YouTube 视频并且只有 id,那么您需要在前面加上 https://www.youtube.com/embed/,这意味着 iframe 将使用 https://www.youtube.com/embed/some_video_id

    <iframe width="100%" height="100%" src= "https://www.youtube.com/embed/<%=project.video_url%>"</iframe>
    

    也可能值得将其移动到一个函数中,这样如果 YouTube 更新其嵌入 URL,您只需在一个地方进行更改。

    【讨论】:

    • 出于您提到@Gazler 的原因,我肯定会将该调用包装在函数中。调用函数是实现 DRY 的好方法。
    • 感谢 Gazler,这有所帮助。我的原始代码适用于特定视频的绝对路径,但是当我调用保存在数据库中的 youtube url 时,它们不会显示。使用您编写的代码行会将我链接到一个空白的 youtube 视频。我想我会改用 Chris Mccord 的 Phoenix 书中的例子。
    【解决方案2】:

    用这个解决了:

    <% video_string = to_string(project.video_url) %>
     <% video = String.slice(video_string,32,String.length(video_string)) %>
     <iframe width="100%" height="100%" position= "absolute"  src="https://www.youtube.com/embed/<%=video%>"></iframe> 
    

    【讨论】:

    • 也许不是最佳做法,但目前是一种解决方法。