-2

I have recently reading someone code. In his code I see a weird html text written like {VARIABLE} . What is that syntax mean? and how to create it? Thanks

rahmat
  • 1,727
  • 16
  • 35

2 Answers2

1

In PHP, there's something called "Complex (curly) syntax" (look for this deeper in the page) where you inject variable's values into strings using {} instead of cutting and concatenating the string.

A similar answer can be found here


Another case is that the HTML could contain that text is when it is used as a template, like this one in CodeIgniter.

Community
  • 1
  • 1
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • 1
    Very true (so a +1 for the link). It would still have to be `{$variable}` or derivates, though, and only applies to strings (not the "non-PHP" portions). –  Sep 12 '12 at 04:09
  • @pst Missed that detail. So this makes this case more like a template for an engine. – Joseph Sep 12 '12 at 04:12
0

You don't initialize it. It's part of their templating engine.

Regardless of how they are doing it, the idea is to find/replace "{VAR}" with the actual data you want.

var songTemplate = "<li class=\"track\"><span class=\"num\">{{TRACKNUM}}.</span>" +
                   "<span class=\"title\">{{TITLE}}</span>" +
                   "<span class=\"duration\">{{DURATION}}</span></li>";


var songs = [ { tracknum : 1, title : "Speak to Me/Breathe", duration : "4:13" },
              { tracknum : 2, title : "On the Run", duration : "3:36" },
              { tracknum : 3, title : "Time", duration : "7:01" } ];


function makeTrack (song, template) {
    var track = "";
    track = template.replace("{{TRACKNUM}}", song.tracknum);
    track = template.replace("{{TITLE}}"), song.title);
    track = template.replace("{{DURATION}}", song.duration);
    return track;
}

function trackList (songs, template) {
    var list = "<ul class=\"tracklist\">";
    songs.forEach(function (song) {
        list += makeTrack(song, template);
    });
    list += "</ul>";
    return list;
}


var songlist = trackList(songs, songTemplate);
parentEl.innerHTML = songlist;

The basic idea, regardless of what language is used to template it, is that you start with a string of HTML, pull out what you know you want to replace, and put in the data that you want.

I've shown you an ugly, ugly template (it'd be better if I only had to write in an array of variable names, and it did the rest... ...or if it looked through the string to find {{X}} and then looked through an object for the right value to replace what it found). This also has security holes, if you don't control both the template and the data (if you allow for end-user input anywhere on your site, then you don't have control).

But this should be enough to show how templates do what they do, and why.

Norguard
  • 26,167
  • 5
  • 41
  • 49