0

Let me explain first what I'm trying to do. Because if there's a better way to achieve this, I'm all ears (or eyes actually).

I've built a (html) template parser of sorts. What I can do is write html templates for webpages and include pieces of code from other templates. Something like this:

<div id="banner">
  %include ads.tmpl bannerad%
</div>

Dis will insert a section (bannerad) from the template file ads.tmpl. And the section in ads.tmpl looks something like this:

<bannerad>
  <div style="width:640px;height:60px">
    <img src="getbanner.cgi?type=genericad">
  </div>
</bannerad>

That way I can include the same banner code on multiple pages and if I ever want to change the look/feel of the banners, there's only one place I have to chance it. This all works fine.

But now I need to be able to identify where a banner is requested. For obvious reasons, I would like to distinguish between say for instance the top of the home page, and somewhere in between text on a sub page.

My idea was to add some identification to the parent container. Something like this:

<div id="banner" data-banner_position_id="MAINPAGE_TOP">
  %include ads.tmpl bannerad%
</div>

And then with inline script in the bannercode, iterate through the banners' parentNodes until it finds data-banner_position_id. Something like this:

<bannerad>
  <div style="width:640px;height:60px">
    <img id="bannerimg">
  </div>
  <script>
    var el = this;
    while( el ) {
      var id = el.dataset.banner_postition_id;
      if( id ) {
        document.getElementById("bannerimg").src = "getbanner.cgi?type=genericad&id=" + id;
        break;
      } else {
        el = el.parentNode;
      }
    }
  </script>
</bannerad>

Now this doesn't work obviously (for several reasons). But is there a way to get this to work? Or is there a better way to do this? It is BTW, completely likely that a page will display more than one banner on a single page...

Zippy1970
  • 601
  • 6
  • 20
  • When does the parsing happen? On the server, so that the HTML sent to the browser has a `script` tag (or tags) in it? Or later, on the browser? – T.J. Crowder Jun 25 '19 at 10:20
  • I've assumed you're doing this server-side, before sending HTML to the client, and so I've marked it as a duplicate of the question for how to get the currently-executing `script` tag (see [this answer](https://stackoverflow.com/a/22745553/157247) in particular). – T.J. Crowder Jun 25 '19 at 10:27
  • Parsing of the templates happens server side. – Zippy1970 Jun 25 '19 at 11:32

0 Answers0