vibe-d / vibe.d

Official vibe.d development
MIT License
1.15k stars 284 forks source link

Render a page without Diet in WebInterface ? #1480

Open SkyzohKey opened 8 years ago

SkyzohKey commented 8 years ago

Hi dudes, Before exposing my problem, I want to give what you deserve to: Thanks for this awesome work!

My "issue" here is that i would like to not use Diet templates. I imported mustache-d successfully, but now I don't know how I can use the result of Mustache.render and display it on my page. It seems that HTTPServerResponse.writeBody() would do the job but i don't understand how I can get a copy of the res object while being inside a WebInterface.

Here's my current code:

class WebInterface {
  private void renderTemplate(string file, Mustache.Context ctx)(HTTPServerResponse res) {
    Mustache mustache;
    mustache.path = "../views/";

    auto html = mustache.render(file, ctx);
    res.writeBody(html, 200, "text/html, charset=UTF-8");
  }

  @method(HTTPMethod.GET) @path("/")
  void index() {
    auto context = new Mustache.Context;
    res.renderTemplate("index", context);
  }
}

So, the error dmd is telling me is:

source/app.d(10,3): Error: undefined identifier 'res'

Thanks for the future replies ;)

s-ludwig commented 8 years ago

You can define a parameter of type HTTPServerResponse (or also HTTPServerRequest) and it will automatically get the current request:

  @method(HTTPMethod.GET) @path("/")
  void index(HTTPServerResponse res) {
    auto context = new Mustache.Context;
    res.renderTemplate("index", context);
  }
BenjaminSchaaf commented 7 years ago

With #1938 (for issue #1937), you can access the global response object. That would allow you to write a render function similar to the one in vibe.web.web.