How To Dynamic Web Rendering?

Adam D. Ruppe destructionator at gmail.com
Tue May 17 10:10:29 PDT 2011


Jacob Carlborg wrote:
> That would require a lot of otherwise (possibly) unnecessary
> id/class attributes (if they aren't removed).

Not that much in the sites I've done.

Here's another real example, that new d web site discussed on the
newsgroup a while ago:

Dynamic page:
http://arsdnet.net/d-web-site/

The HTML template it manipulates with DOM:
http://arsdnet.net/d-web-site/index.html


There's only three dynamic elements on that page, so the template
is almost identical to the finished page.

There's three placeholders getting filled in:

<div id="announcements" />
<div id="commits" />

and <form id="code-runner">



And the relevant code:

form:

  auto f = cast(Form) document.getElementById("code-runner");
  f.setValue("code", `void main() { assert(0, "Hello, world!"); }`);


It fills the form, without caring about how the form is written.
This does name="code" and sets value to that string given. It
doesn't care how the HTML is written - here, it's a <textarea>,
but this code remains the same if it's an <input> or <select>.

The view controls how the data is presented, the dom just tells
it what to present.


Announcements and commits are done with more dom calls, but still,
not much.

void addAnnouncements(Element holder) {
  auto document = holder.parentDocument;

  foreach(announcement; getAnnouncements()) {
    auto h = holder.addChild("div");

    auto date = std.date.parse(announcement.date);

    h.addChild("span", formatDate(date));
    h.appendText(" - ");
    h.appendChild(new Link(announcement.url, announcement.subject));
  }
}

Commits is a little longer since it has more data, but same idea.


Arguably, this crosses the line into presentation, especially
with that appendText call. (I guess it could do an #announcements >
span:after in css, but that's not reliable) But, you can see
that the vast majority of html is far away from here.

The #announcements id used to fill it in is also used to style
the inside:

#announcements > div { style each announcement }
#announcements > div > span { style the date }
#announcements > div > a { style the link }


(man, css nesting is such a good thing to have!)




Side note: obviously, you don't *have* to do web apps my way, even
with my libraries. cgi.d is template-agnostic. dom.d isn't going
to kill you if you ask it to add logic to templates or do string
replacement instead.

My way is just one possibility of many.


More information about the Digitalmars-d-learn mailing list