Developer forum

Forum » Templates » Razor: Increment

Razor: Increment

Jacob Storgaard Jensen
Reply

Hi, I've got a template which is both used as an include on a normal ecom product catalog template and on product templates...
What I would like to achieve is to have my wrapping element given a unique ID each time this include/template is rendered. So if rendered 3 times on the same page, each element gets a unique id - ie:

<div id="uniquenumber">my stuff</div>

Is there in Razor a way to have some kind of way/function to stores the initial value, and each time it's called it increments by +1 and outputs that value?
Would be nice if possible to do like this RenderUniqueID("SomeCSSText") resulting in ie: SomeCSSText123

PS: the uniqueness of these numbers only need to be related to each page load... so i.e. if paragraphs are sorted differently the id's dont have to stick to the item/paragraph... they only need to be unique on that page and that page load...


Replies

 
Jacob Storgaard Jensen
Reply

Well, solved it myself:

In top of the template that might be rendered multiple times throughout a page, I have this code:

@{
    init();
}

@functions {
    private int templateRenderCounter { get; set; }

    public void init()
    {
        templateRenderCounter = Dynamicweb.Core.Converter.ToInt32(System.Web.HttpContext.Current.Items["templateRenderCounter"]);
        System.Web.HttpContext.Current.Items["templateRenderCounter"] = templateRenderCounter;
    }
}

Then in the actual html markup I put in the "counter" whereever I need it with @templateRenderCounter :

<div id="SomeCSSText-@templateRenderCounter">my stuff</div>

Then somewhere after I've used the tag for the last time in this template, I increments the counter, and store the incremented value for the next time the template is rendered on that page (if rendered at all - doesn't matter):

System.Web.HttpContext.Current.Items["templateRenderCounter"] = templateRenderCounter +1;
There might be "wrongdoings" in there, so if you see any, please point them out - but it renders the intended

 

You must be logged in to post in the forum