A Simple Webpage
Hello World is a good start, but what if you want something a bit more fancy.. Something like an HTML document saying "Hello World". If that's what you want, follow along:
Basic Webpage¶
Let's start our webpage with.. well.. a webpage. But before we create a webpage we need to place it somewhere Crow recognizes, for now this directory is going to be called templates, but we can change it later.
Once our templates folder is created, we can create our HTML document inside it, let's call it fancypage.html.
After that we can just place something simple inside it like:
<!DOCTYPE html>
<html>
<body>
<p>Hello World!</p>
</body>
</html>
Now that we have our HTML page ready, let's take our Hello World example from earlier:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
And now let's modify it so that it returns our cool page:
| /main.cpp | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
Your project should look something something like:
./
|-templates/
| |-fancypage.html
|
|-main.cpp
|-crow_all.h
./
|-templates/
| |-fancypage.html
|
|-crow/
| |-include/...
| |-crow.h
|-main.cpp
Once the code is done compiling, if we call http://localhost:18080/ we get our Hello World in an HTML document rather than just plain text.
Template Webpage with a variable¶
But we can make things even more exciting, we can greet a user by their name instead!!
Let's start with our webpage, and modify it with a little bit of mustache syntax:
<!DOCTYPE html>
<html>
<body>
<p>Hello {{person}}!</p> <!--(1)-->
</body>
</html>
{{}}in mustache define a simple variable
Now let's modify our C++ code to use the variable we just added to our webpage (or template):
| /main.cpp | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
- We are adding a
stringvariable to the URL and a counterpart (std::string name) to our route - this can be anything the user wants. - We are using
load()instead ofload_text()since we have an actual variable now. - We are creating a new context containing the
personvariable from our template and thenamewe got from the URL. - We are using
render(ctx)to apply our context to the template.
Now (after compiling the code and running the executable a second time) calling http://localhost:18080/Bob should return a webpage containing "Hello Bob!". We did it!
For more details on templates and HTML pages in Crow please go here