Display a random image with vibe.d

vnr cfcr at gmail.com
Sun Jun 20 12:34:33 UTC 2021


Hello,
I would like to display a random image each time a page is 
refreshed. I think my random function works, but the image does 
not appear on the page. I have this template:

```
/public
     /images
         /rndimg
             img1.jpg
             img2.jpg
             img3.jpg
/source
     app.d
/views
     index.dt
```

index.dt:

```
doctype html

html(lang="en")
     head
         meta(charset="UTF-8")
         meta(name="viewport", content="width=device-width, 
initial-scale=1.0")
         meta(http-equiv="X-UA-Compatible", content="ie=edge")
         title Document
     body
         img(src='#{rndimg}')
```

And the code itself is:

```
import vibe.vibe;

void main()
{
	auto settings = new HTTPServerSettings;
	settings.port = 8080;
	settings.bindAddresses = ["::1", "127.0.0.1"];
	auto listener = listenHTTP(settings, &index);
	scope (exit)
		listener.stopListening();

	logInfo("Please open http://127.0.0.1:8080/ in your browser.");
	runApplication();
}

/// The index page
void index(HTTPServerRequest req, HTTPServerResponse res)
{
	import std.random;
	import std.format;
	
	auto rnd = Random(unpredictableSeed);
	auto a = uniform(1, 3, rnd);
	const auto rndimg = format("images/rndimg/img%d.jpg", a);

	res.render!("index.dt", req, rndimg);
}
```

I don't understand why the image doesn't display, when I take an 
image from the internet and give the url, it works fine though.

Also, is this a good way to randomly display an image or is there 
a way that is maybe cleaner/efficient?

Thank you.


More information about the Digitalmars-d-learn mailing list