Rendering Media
Templates (Views) can access items in the Media library to assist in displaying rich content like galleries.
In the following examples we will be looking at rendering an Image
.
Image is only one of the 'types' of Media in Externable. The same principles apply to all MediaTypes (however the actual properties available to render will be different, for example a File
won't have a Width property).
Rendering a media item
A media item is not only a reference to a static file, but like content, it is a collection of fields, such as width, height and the path to the stored file. This means that accessing and rendering media in a template is very similar to rendering content.
Example 1: Accessing a Media Image IPublishedContent item based upon its Id
An uploaded image in the media library is based on the MediaType Image
which has defined a number of standard properties:
- Name
- Width & Height
- Size
- Type (based on file extension)
- UmbracoFile (the path to the file or Json data containing crop information) These standard properties are pre-populated and set during the upload process, eg the width and height are calculated for you.
If you want to add further custom properties, eg 'Photographer Credit' to use with your Media Item, edit the Image MediaType under settings. In this example we are going to retrieve an image from the Media section and render out an img
tag using the URL of the media item and making use of the Name as the value for the alt
attribute.
Assumption: We are going to assume that our media item has an ID of 1234, and that we are not using Models Builder.
@{
// The Umbraco Helper has a Media method that will retrieve a Media Item by Id in the form of IPublishedContent, in this example the Media Item has a unique id of 1234:
var mediaItem = Umbraco.Media(1234);
}
@if (mediaItem!=null)
{
// To get the url for your media item, you use the Url property:
var url = mediaItem.Url;
// to read a property by alias
var imageHeight = mediaItem.Value<int>("umbracoHeight");
var imageWidth = mediaItem.Value<int>("umbracoWidth");
var orientationCssClass = imageWidth > imageHeight ? "img-landscape" : "img-portrait";
<img src="@url" alt="@mediaItem.Name" class="@orientationCssClass"/>
}
File
Other Media Items such as Accessing other media items can be performed in the same way, the techniques aren't limited to the Image
type, but it is one of the most common use cases.
Image Cropper
Image Cropper can be used with Image
media types and is the default option for the umbracoFile property on an Image
media type.
When working with the ImageCropper for an image the GetCropUrl
extension method is used to retrieve, cropped, resized versions of the uploaded image. Details of the Image Cropper property editor and other examples of using it can be found here.