Mike Robbins

Sitecore Developer Blog

Follow me on GitHub

Sitecore YouTube Control

A very simple and useful YouTube control for Sitecore for embedding YouTube videos. You can either specify a Sitcore item to get the YouTube ID field from, otherwise it will use the context item.

  1. Create a class using the code below
  2. Register the control in the web.config
      <controls>
        <add tagPrefix="TB" namespace="ToolBox.SitecoreCMS.Web.UI.WebControls" assembly="ToolBox.SitecoreCMS" />
      </controls>
      
  3. Use the control within your sublayouts
        <tb:YouTube runat="server" Field="YouTubeID" Height="200" Width="400"/>
      

register the control within the web.config and use it within your sublayouts.

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sitecore.Data.Items;
namespace ToolBox.SitecoreCMS.Web.UI.WebControls
{
  public class YouTube : WebControl
  {
    public Item Item { get; set; }
    public string Field { get; set; }
    public override Unit Height { get; set; }
    public override Unit Width { get; set;}

    protected override void Render(HtmlTextWriter writer)
    {
      writer.Write(BuildYouTube());
    }

    private string BuildYouTube()
    {
      return "<i frame width='" + Convert.ToInt32(Width.Value) + "px' height='" + Convert.ToInt32(Height.Value) + "px' src='http://www.youtube.com/embed/" + GetYouTubeVID() + "' frameborder='0' allowfullscreen></i frame>";
    }

    private string GetYouTubeVID()
    {
    return Item != null ? Item[Field] : Sitecore.Context.Item[Field];
    }
  }
}