---
title: Render variants with the Xperience tag helpers
---

> **Documentation indexes**
> The indexes below list current page URLs with titles and descriptions. Links on this page point to the Markdown versions of the linked pages.
>
> - [sitemap.md](https://docs.kentico.com/sitemap.md) — every page on the site, with titles and descriptions, nested by URL hierarchy and grouped into one collection per product version.
> - [llms.txt](https://docs.kentico.com/llms.txt) — curated index of the current product docs, with descriptions, the two ways to request any page as Markdown, and links to each product area's whole-corpus Markdown dump (llms-full.txt).

Your Razor views control which image variant the browser downloads for each placement on a page. A single uploaded photo can appear as a square crop on a phone, a wide hero banner on a desktop monitor, and a compact 4:3 card in a listing grid.

By the end of this material, you'll pass image assets and their variants into your view models, render fixed crops and hero banners that switch crops using the built-in Xperience by Kentico tag helpers, and create a custom `<tg-responsive-image>` tag helper that outputs a multi-width `srcset`.

![The Image variants showcase page at a 1440 px wide viewport: a wide hero banner across the top, a 4:3 card below it, and a container-wide responsive image under that, all three showing the same photo of farfalle with pesto.](https://docs.kentico.com/docsassets/modules/render-variants-with-xperience-tag-helpers/Showcase_Page_1440.jpg "The image variants showcase at a 1440 px viewport")

## Explore the showcase

In the _Training guides_ repository, the _Image variants_ page (under _News and articles_) uses the _Image variants showcase_ page template to render the same article teaser photo in three different layouts:

- A hero banner that switches from a square crop on phones to a wide landscape crop on larger viewports.
- A card with a fixed 4:3 crop.
- A responsive image that scales with its image area width and the screen's pixel density.

The implementation lives under `Features/ResponsiveImages` in the `TrainingGuides.Web` project, with view models in `Models`, the tag helper in `TagHelpers` and the showcase view component in `ViewComponents`. The page template renders the showcase view component above its main editable area:

```razor title="ImageVariantsShowcasePageTemplate.cshtml"
@using TrainingGuides.Web.Features.Articles

@model TemplateViewModel

...
<vc:image-variants-showcase />
<div>
    <editable-area area-identifier="areaMain" />
</div>
```

Although the showcase uses a view component inside a [page template](https://docs.kentico.com/documentation/developers-and-admins/development/builders/page-builder/page-templates-for-page-builder.md), the same tag helpers work in any Razor view covered by your `@addTagHelper` directive, including standard MVC views, Page Builder widgets, and sections.

## Pass the asset to the view

### Carry the asset and its alt text

When Xperience maps an asset field onto a generated content type class, it populates a `ContentItemAsset` property directly from the item's stored metadata. That object carries the original file URL, the dictionary of variant URLs (`VariantUrls`), and the stored pixel dimensions (`Metadata`) for both the original image and each variant.

Because Xperience's built-in `kxp-img` tag helpers accept a `ContentItemAsset` instance, include the `ContentItemAsset` object directly on your view models so your views have access to every variant URL and its stored dimensions.

`ContentItemAsset` only describes the file binary and its variants; alternative text lives in a separate field on the content type, such as `AssetAltText` on the _Asset_ type in the _Training guides_ repository. Define a small record that pairs `ContentItemAsset` with its alt text:

```csharp title="ImageViewModel.cs"
using CMS.ContentEngine;

namespace TrainingGuides.Web.Features.ResponsiveImages.Models;

/// <summary>
/// Pairs an image asset with its alternative text for rendering in views.
/// </summary>
/// <param name="Asset">The image asset, including its variant URLs and dimension metadata.</param>
/// <param name="AltText">Alternative text for the image, or an empty string for decorative images.</param>
public record ImageViewModel(ContentItemAsset Asset, string AltText)
{
    /// <summary>
    /// Creates an <see cref="ImageViewModel"/> from an <see cref="Asset"/> content item.
    /// </summary>
    /// <param name="asset">The source Asset content item, or <c>null</c>.</param>
    /// <returns>
    /// A populated <see cref="ImageViewModel"/>, or <c>null</c> if the item or its file is missing.
    /// Null alternative text is normalized to an empty string.
    /// </returns>
    public static ImageViewModel? GetViewModel(Asset? asset) => asset?.AssetFile is null
        ? null
        : new(asset.AssetFile, asset.AssetAltText ?? string.Empty);
}
```

`ImageVariantsShowcaseViewModel` holds the article's `Title` and an optional `ImageViewModel?`, which remains `null` if the page has no linked article or teaser asset.

### Retrieve the image with enough linked-item depth

On an article page, the teaser image is two reference hops away from the page itself: `ArticlePage` references the article content item (`ArticlePageArticleContent`), which in turn references the reusable _Asset_ item (`ArticleSchemaTeaser`).

![Content model of the image variants showcase. The ArticlePage page content type, retrieved by RetrieveCurrentPage, is level 0. Its ArticlePageArticleContent field references an article item that implements IArticleSchema, a GeneralArticle or Interview, at level 1. The article's ArticleSchemaTeaser field references an Asset item of a reusable content type, with the AssetFile field holding the image and its variants and the AssetAltText field, at level 2. Each reference adds one level.](https://docs.kentico.com/docsassets/modules/render-variants-with-xperience-tag-helpers/Image_Variants_Showcase_Content_Model.drawio.svg "Content model of the image variants showcase")

When querying content with `RetrieveCurrentPage`, linked-item depth starts at level 0 for the page itself and increments by one for each reference hop. Reaching the _Asset_ item therefore requires a maximum linked-item level of `2`. At depth `1`, the query loads the article item and leaves its `ArticleSchemaTeaser` property `null`.

In the _Training guides_ repository, `IContentItemRetrieverService.RetrieveCurrentPage` forwards its depth argument to `RetrieveCurrentPageParameters.LinkedItemsMaxLevel`. `ImageVariantsShowcaseViewComponent` requests depth `2` to load the teaser asset:

```csharp title="ImageVariantsShowcaseViewComponent.cs"
using System.Linq;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Mvc;

using TrainingGuides.Web.Features.ResponsiveImages.Models;
using TrainingGuides.Web.Features.Shared.Services;

namespace TrainingGuides.Web.Features.ResponsiveImages.ViewComponents;

/// <summary>
/// Renders the current article page's teaser image using both the built-in Xperience
/// image tag helpers and the custom responsive image tag helper.
/// </summary>
/// <param name="contentItemRetrieverService">Service used to retrieve the current page.</param>
public class ImageVariantsShowcaseViewComponent(
    IContentItemRetrieverService contentItemRetrieverService)
    : ViewComponent
{
    // Level 0: ArticlePage -> Level 1: article item -> Level 2: teaser Asset item.
    private const int TEASER_ASSET_DEPTH = 2;

    /// <summary>
    /// Retrieves the current article page and maps its title and teaser image.
    /// </summary>
    /// <returns>The showcase view result.</returns>
    public async Task<IViewComponentResult> InvokeAsync()
    {
        var articlePage = await contentItemRetrieverService
            .RetrieveCurrentPage<ArticlePage>(TEASER_ASSET_DEPTH);
        var article = articlePage?.ArticlePageArticleContent.FirstOrDefault();

        var model = new ImageVariantsShowcaseViewModel
        {
            Title = article?.ArticleSchemaTitle ?? string.Empty,
            Image = ImageViewModel.GetViewModel(article?.ArticleSchemaTeaser.FirstOrDefault())
        };

        return View("~/Features/ResponsiveImages/ViewComponents/ImageVariantsShowcase.cshtml", model);
    }
}
```

Fetching the page inside the view component lets the showcase page template work alongside any controller that serves `ArticlePage`. In your own page controllers, you can map `ImageViewModel` directly onto the page view model and pass it down to your views.

For more details on linked content retrieval, see [Retrieve linked content items](https://docs.kentico.com/documentation/developers-and-admins/development/content-retrieval/retrieve-content-items.md#retrieve-linked-content-items).

> **Note:** If you restrict a query's columns with `Columns(...)`, always include `ContentItemGUID` and `ContentItemCommonDataContentLanguageID`. Xperience requires both columns when constructing a `ContentItemAsset`.

## Render variants with the Xperience tag helpers

The `kxp-img` attribute [tag helpers](https://docs.kentico.com/documentation/developers-and-admins/development/reference-tag-helpers.md) render a single image variant on an `<img>` element or on a `<source>` element inside `<picture>`:

- `kxp-img-variant` – accepts a variant code name and writes that variant's URL to `src` (on `<img>`) or `srcset` (on `<source>`). Referencing code names from your constants class prevents typos at compile time.
- `kxp-img-dimensions` – outputs the variant's stored `width` and `height` attributes so the browser reserves layout space ahead of the image download.

Because the `kxp-img` tag helpers only manage `src`/`srcset`, `width`, and `height`, always include explicit `alt` and `loading` attributes on the `<img>` element.

### Switch crops on phones with a picture element

A wide 16:9 hero banner often crops out the subject when scaled down to a narrow phone screen. Using a `<picture>` [element](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/picture), you can serve a square crop below a mobile breakpoint and the wide crop on larger viewports:

```razor title="ImageVariantsShowcase.cshtml (hero banner)"
@using TrainingGuides.Web.Features.ResponsiveImages
@using TrainingGuides.Web.Features.ResponsiveImages.Models

@model ImageVariantsShowcaseViewModel

@if (Model.Image is { } image)
{
    ...
    <picture>
        <source media="(max-width: 575.98px)"
            kxp-img="@image.Asset"
            kxp-img-variant="@ImageVariants.HERO_MOBILE_828X828"
            kxp-img-dimensions="true" />
        <img kxp-img="@image.Asset"
            kxp-img-variant="@ImageVariants.HERO_WIDE_1920X1080"
            kxp-img-dimensions="true"
            alt="@image.AltText"
            loading="eager"
            class="img-fluid" />
    </picture>
    ...
}
```

Because the hero banner is the primary above-the-fold image on the page, set `loading="eager"` on the inner `<img>` element. The `<source>` element supplies the mobile crop for viewports under `576px`, while the `<img>` element provides the default desktop crop along with the shared `alt` and `loading` attributes.

![The hero banner of the showcase at a 1440 px wide viewport: the HeroWide1920x1080 crop shows a white plate of farfalle with basil pesto and cherry tomatoes on the right and the bare tabletop on the left.](https://docs.kentico.com/docsassets/modules/render-variants-with-xperience-tag-helpers/Showcase_Hero_Wide_1440.jpg "Wide crop of the hero at a 1440 px viewport")

![The same hero at a 390 px wide viewport: the HeroMobile828x828 square crop fills most of the frame with the pasta and tomatoes, with only a strip of tabletop on the left.](https://docs.kentico.com/docsassets/modules/render-variants-with-xperience-tag-helpers/Showcase_Hero_Phone_390.jpg "Square crop of the hero at a 390 px viewport")

### Show a fixed crop in a card

For a card component with a fixed aspect ratio, apply `kxp-img` and `kxp-img-variant` directly to an `<img>` element, and set `loading="lazy"` for cards rendered below the fold:

```razor title="ImageVariantsShowcase.cshtml (card)"
@using TrainingGuides.Web.Features.ResponsiveImages
@using TrainingGuides.Web.Features.ResponsiveImages.Models

@model ImageVariantsShowcaseViewModel

...
<div class="c-card_img">
    <img kxp-img="@image.Asset"
        kxp-img-variant="@ImageVariants.CARD_800X600"
        kxp-img-dimensions="true"
        alt="@image.AltText"
        loading="lazy"
        class="img-fluid" />
</div>
...
```

> **Warning:** `kxp-img-variant` performs a case-sensitive lookup against the asset's variants. If the specified code name does not match a variant on the asset, the tag helper silently falls back to the full-size original image URL and omits the `width` and `height` attributes.
