Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Template Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Avoiding Duplicate HTML ElementIDs when reusing widgets & included templates

Go to End

2 Posts   2950 Views


Community Member, 62 Posts

12 November 2011 at 7:48am

Edited: 12/11/2011 7:52am

I understand about result caching in templates, as described in and how we cannot rely on things like counters, etc. to guarantee unique values for use in a template. But how do we create unique values in template includes when reusing them, such as HTML Element IDs, which must be unique for scripting to work properly?

Here is my scenario: Let's say I have a template include called "". Inside this include file is HTML something like:

<div id="element-id-X"><otherHTML /></div>
    var widgetDivId = document.getElementById('element-id-X');

Now imagine that you may need to include the same widget any number of times on the page. Each time, the javascript must refer only to that HTML that is bundled with it -- so obviously the "X" value in the above is something like a number, and different every time. And these are not necessarily part of a sequence of objects, so there is really no <% control Children %> or anything like that.

This scenario is becoming more frequent as I start to bring in things like Google Custom Search scripting, Disqus elements, etc. One example (though not the only one) is a that is included in the outer "chrome" of the site (IOW the that is in the template root folder.) However, there are other pages in the site that will also use *another* on the main page -- styled larger, but otherwise exactly the same, so it would be wrong from a code reuse POV to have a different SS file for that one.


Community Member, 78 Posts

22 November 2011 at 8:11am

Edited: 22/11/2011 8:13am

Doesn't every widget instance provide an "unique" ID (because of its auto-increment field)?

If so, it would be enough to do it this way

<div id="element-id-$ID"><otherHTML /></div>
var widgetDivId = document.getElementById('element-id-$ID');