Copied to clipboard

Flag this post as spam?

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


  • Steve 472 posts 1216 karma points
    Jan 11, 2013 @ 17:30
    Steve
    0

    Pulling random Images from a media folder and displaying them as background images

    My razor script won't even load into the page. I am new to razor-could someone check my syntax? Thanks

    @{

    if (Model.imageRotatorFolder.Children.Count() > 0) {

    <style type="text/css">

    .welcome {

    background: url(foreach(var image in Model.imageRotatorFolder.Children.Random(4)) {

    image.Media("","umbracoFile");

    }

    ) left top no-repeat;

    }

    </style>

    }

    }

  • Jan Skovgaard 11280 posts 23678 karma points MVP 11x admin c-trib
    Jan 12, 2013 @ 13:24
    Jan Skovgaard
    0

    Hi Steve

    What version of Umbraco are you using? If it's 4.10 or higher then what template mode are you using? Webforms or Razor views? The reason I ask for this is because since v4.10 was released there now is macroscript razor and mvc razor and the way to access the model etc. differs from these two versions :)

    /Jan

  • Steve 472 posts 1216 karma points
    Jan 14, 2013 @ 14:12
    Steve
    0

    Jan,

    We are using 4.11.1 and I don't know what the tempate mode is as I don't have access to the install folder.

  • Greg McMullen 49 posts 195 karma points
    Jan 17, 2013 @ 20:26
    Greg McMullen
    1

    Luckily we were able to put our heads together and figure it out.

    @using umbraco.MacroEngines
    @inherits umbraco.MacroEngines.DynamicNodeContext
    @{

    var mediaFolderId = Model.imageRotatorFolder;

    dynamic folder = Library.MediaById(mediaFolderId);

    var randomImage = folder.Children.Where("nodeTypeAlias = \"Image\"").Random();
    <style type="text/css">
    .welcome{
    background:url(@randomImage.UmbracoFile) top left no-repeat;
    }
    </style>
    }
  • Greg McMullen 49 posts 195 karma points
    Jan 17, 2013 @ 21:18
    Greg McMullen
    1

    And now it's taking into account if someone removes and image, without removing the media altogether.

     @using umbraco.MacroEngines
    @inherits umbraco.MacroEngines.DynamicNodeContext
    
    @{  
    @* Grab the folder ID *@
    var mediaFolderId = Model.imageRotatorFolder;
    
    @* Make the ID Dynamic (for access to media files) *@
    dynamic folder = Library.MediaById(mediaFolderId);
    
    @* Grab images that are not null and are in fact "Image" *@
    var images = folder.Children.Where("nodeTypeAlias = \"Image\" && umbracoFile != null");
    
    @* Select a random image to display (Will change on every refresh) *@   
    var randomImage = images.Random();
    
        <style type="text/css">
            .welcome{
                background:url(@randomImage.UmbracoFile) top left no-repeat;
            }
        </style>
    }

     

Please Sign in or register to post replies

Write your reply to:

Draft