Converting a regular Youtube 'link' into an embedded video

前端 未结 10 1848
别那么骄傲
别那么骄傲 2021-01-30 02:25

My goal: I am trying to allow users to embed a link to a Youtube video in my site, while giving me control over the player\'s settings.

I would like to do this by only a

10条回答
  •  终归单人心
    2021-01-30 03:09

    something like this (for ex. in model):

    @@video_regexp = [ /^(?:https?:\/\/)?(?:www\.)?youtube\.com(?:\/v\/|\/watch\?v=)([A-Za-z0-9_-]{11})/, 
                       /^(?:https?:\/\/)?(?:www\.)?youtu\.be\/([A-Za-z0-9_-]{11})/,
                       /^(?:https?:\/\/)?(?:www\.)?youtube\.com\/user\/[^\/]+\/?#(?:[^\/]+\/){1,4}([A-Za-z0-9_-]{11})/
                       ]
    
    def video_id
      @@video_regexp.each { |m| return m.match(source_url)[1] unless m.nil? }
    end
    

    where source_url is the full link to video. then a helper:

    def youtube_video(video_id)
      render :partial => 'youtube_video', :locals => { :id => video_id }
    end
    

    and sample partial (haml):

    %iframe{:allowfullscreen => "", :frameborder => "0", :height => "349",
            :src => "http://www.youtube.com/embed/#{id}", :width => "560"}
    

    and in view as simple as:

    = youtube_video Model.video_id
    

提交回复
热议问题