Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Hubert Thalmann 57 posts 261 karma points
    Sep 13, 2016 @ 09:58
    Hubert Thalmann
    0

    Media Picker, CSS, Background URL

    Hello our.Umbraco

    I have a Question.

    Is there a way to make a new Documenttype with 3-4 Mediapickers where i can choose images from the Media Library and then put these Images into my CSS at for example:

    .myclass{
    background-image: url(HERE_COMES_THE_PATH);
    }
    

    is there a way to do that?

  • Sven Geusens 169 posts 878 karma points c-trib
    Sep 13, 2016 @ 15:02
    Sven Geusens
    1

    I don't think you can, since a css file is not a razor file. So what is left is either inline or defining the css in the page and reusing it.

    If you are going to use one of the pictures on any page I would just define it on your master. Somewhere in your head where you load your other css files you can add a razorscript like the following

    @{
        var settingsNode = Umbraco.TypedContentAtRoot().FirstOrDefault(i => i.DocumentTypeAlias == "settings"); //Presuming you have a node with documentType "settings" at the root level
        if (settingsNode != null)
        {
            <style>
    
                @if (settingsNode.HasValue("backgroundpicture1")) //Check if the image has been set
                {
                    var bgp1 = settingsNode.GetPropertyValue < IPublishedContent > ("backbackgroundpicture1");
                    // Only works if you have our.umbraco,corevalueconverters installed
                    // else use this: var bgp1 = Umbraco.TypedContent(settingsNode.GetPropertyValue("backbackgroundpicture1"));
                    @Html.Raw(".myclass{background-image: url(" + bgp1.Url + ");}");
                }
    
            </style>
        }
    }
    

    If you are only going to use this on some pages, you can add a @RenderSection("Css", false) in this scripts place and add the script to the template page with starting with @section Css{ instead of @{

  • Dennis Aaen 4492 posts 18198 karma points admin hq c-trib
    Sep 13, 2016 @ 15:11
  • Tim Miller 32 posts 252 karma points
    Sep 13, 2016 @ 16:30
    Tim Miller
    100

    Just as an added safety check you should check to see if the media item is null. If you select an image using the media picker and then the image is later deleted from the media section, your page will throw an error. Here's a snippet showing how I do it:

    if(CurrentPage.HasValue("image"))
    {
        IPublishedContent image = Umbraco.TypedMedia(CurrentPage.image);
    
        if(image != null)
        {
            <style>
                .myclass { background-image: url(@image.Url); }
            </style>
        }
    }
    
Please Sign in or register to post replies

Write your reply to:

Draft