Skip to content

Named configuration expression #7

@benfoster

Description

@benfoster

To support HTML5 srcset, sizes and <picture> element it should be possible to define named expressions when configuring an ImageUrlBuilder instance.

Right now if we were to use srcset we'd have to do something like this:

<img src="@Url.ImageUrl("image.jpg", img => img.Resize(x => x.Width(300)))"
     srcset="@Url.ImageUrl("image.jpg", img => img.Resize(x => x.Width(600))) 2x, @Url.ImageUrl("image.jpg", img => img.Resize(x => x.Width(900))) 3x"
    alt="" />

Of course we can create an image helper for this:

@Html.BuildImage(builder1, "Alt text")
    .AddSrc("2x", builder2)
    .AddSrc("3x", builder3)
    .Render();

This would still require three ImageUrlBuilder instances to be created. More often than not, when working with responsive images, it's just the size that needs to change depending on the resolution or display size. If you're using other configurations (styling, filters etc.) or modifiers, this means you need to define them again for each builder.

A solution to this is to define named configuration expressions that are applied conditionally when building the image URL. For example:

var builder = new ImageUrlBuilder()
        .Resize(img => img.Resize(x => x.Width(300))) // Default
        .Config("2x")
            .Resize(img => img.Resize(x => x.Width(600)))
        .Config("3x")
            .Resize(img => img.Resize(x => x.Width(900)));

var defaultImage = builder.BuildUrl("someimage.jpg");
var retinaImage = builder.BuildUrl("someimage.jpg", "2x");

Alternatively we could require each builder expression to define a configuration key:

var builder = new ImageUrlBuilder()
        .Resize(img => img.Resize(x => x.Width(300))) // Default
        .Resize("2x", img => img.Resize(x => x.Width(600)))
        .Resize("3x", img => img.Resize(x => x.Width(900)));

var defaultImage = builder.BuildUrl("someimage.jpg");
var retinaImage = builder.BuildUrl("someimage.jpg", "2x");

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions