You are not logged in Log in Join
You are here: Home » Members » jim » Generate URLs for Objects

Log in
Name

Password

 

Generate URLs for Objects

(Note that the impatient can jump to the end of the how-to to get the answer without reading through the rational. :)

It's common to need to provide URLs for objects. There are a number of ways that this can be done. You can just give a relative URL using the object name, as in:

  <a href="spam">

This works even if the object spam is not in the current folder but is acquired. A significant disadvantage of this approach is that, if the object is acquired, it can drive persistent spiders insane because it sets up situations where a program following links generates an unlimited sequence of strange but valid URLs.

To see how this can happen, imagine that the above reference appears in the index_html page of the eggs sub-folder of spam. Suppose that spam has an index_html that points to eggs. Now imagine the following spider requests:

  1. Visit spam, see relative reference to eggs
  2. Visit spam/eggs, see relative reference to spam
  3. Visit spam/eggs/spam, see relative reference to eggs
  4. Visit spam/eggs/spam/eggs, see relative reference to spam

    ...

Another problem with relative URLs is that they defeat image caching. To see why, imagine that you have an image in your root folder named logo. You could reference this image using a relative reference:

  <img src="logo">

but this will make logo appear to the cache as a separate object, with a separate URL in each folder.

It's better to use absolute references. An easy way to build an absolute reference is to prepend the request variable URL1, as in:

  <a href="&dtml-URL1;/spam">

But this suffers from the same problem as a relative URL, since it's really still a relative reference.

(Note that we use the entity reference form of the var tag here because we're sticklers for writing, uh, well-formed HTML. We could, instead, have used:

  <a href="<dtml-var spam>">

but this looks too weird and might upset an HTML editior.)

To generate a true absolute reference to an object, you can call it's absolute_url method, as in:

  <dtml-with "_(abs_spam=spam.absolute_url())">
    <a href="&dtml-abs_spam;">
  </dtml-with>

This is good because we get the same URL for spam no matter where we reference it. It also doesn't matter where spam is, as long as we can acquire it.

This version is a bit long-winded. We had to resort to an expression to call absolute_url and we had to use a with tag, because we can't use an expression in an entity reference.

Fortunately, the var tag has an option, url, for inserting the absolute_url of an object. We can use this to simplify the reference quite a bit:

  <a href="&dtml.url-spam;">

So, in summary, when you want to generate a URL for an object, use the entity-reference version of the var tag with the url option.