2

I consistently come across this code smell where I am duplicating markup, and I'm not really sure how to fix it. Here's a typical use case scenario:

Let's say we'd like to post comments to some kind of article. Underneath the article, we see a bunch of comments. These are added with the original page request and are generated by the templating engine (Freemarker in my case, but it can be PHP or whatever).

Now, whenever a user adds a comment, we want to create a new li element and inject it in the current page's list of comments. Let's say this li contains a bunch of stuff like:

  1. The user's avatar
  2. Their name
  3. A link to click to their profile or send them a private message
  4. The text they wrote
  5. The date they wrote the comment
  6. Some "edit" and "delete" links/buttons if the currently logged in user has permission to do these actions.

Now, all of these things were already written in our template that originally generated the page... so now we have to duplicate it inside of Javascript!

Sure, we can use another templating language - like Jquery's Template plugin - to ease the pain generating and appending this new li block... but we still end up with duplicate html markup that is slightly different because we can't use macros or other conveniences provided to us by the templating language.

So how do we refactor out the duplication? Is it even possible, or do we just put up with it? What are the best practices being used to solve this problem?

egervari
  • 22,372
  • 32
  • 121
  • 175
  • It's an interesting question and I'm not sure how to answer it, but two things immediately come to mind. For servers implemented in javascript, coffeekup allows the same template to be used both client-side and server-side (not convinced this is a good solution though). Otherwise, you may simply `.clone()` an existing `
  • ` and populate with new data. The server-side template can generate a special hidden div for this purpose - I don't feel this is messy, it's signalling: "look, this is meant to be reused!"
  • – David Tang Dec 12 '10 at 09:24
  • Well, I don't even know what coffeekup is... but I'm using Tomcat, so I doubt that helps ;) .clone() is an interesting alternative. I guess I could hide the template and stuff it at the button of the *ul* element. I'd have to add more id's or classes to every tag if I did that, but that's not a bad solution. It's better than using jquery's templating plugin for this purpose. I'll try it out and see how much of a hassle it is. The one benefit jquery's template has is that it's easy to do - it just duplicates code. – egervari Dec 12 '10 at 09:33