简体   繁体   中英

Generate static HTML pages with content from text file

I'm playing around with a random joke generator, which loads a random html page with some lame joke. Right now the index page looks like this:

<!DOCTYPE html>
<html>
   <head><title>Jokes</title>
      <link rel="stylesheet" type="text/css" href="styles.css">
      <script>
         function runme() {
            var arr = ["joke1.html", "joke2.html", "joke3.html"];
            var value = arr[Math.floor(Math.random() * arr.length)];
            window.location = value;
         }
       </script>
    </head>
    <body>
       <h1>JOKES</h1>
       <div class="jokebtn">
          <input id="nyjoke" type="button" onclick="runme()" value="Make me laugh!" />
       </div>

    </body>
</html>

When you press the button, it redirects you to a random html page defined in the javascript array.

My question is, how do I generate the HTML pages containing the jokes (just a <p> with some text) from a text document? I'd like to be able to add jokes to a textfile, and then generate the HTML page from that, instead of copy/pasting in a <p> for every page I'd like to add. Also, the page should be static (ie joke2.html always have the same joke), so you save the link/joke for later.

I'm thinking something like yattag for python, but I'm sure there's an easier solution. Maybe php? Any help greatly appreciated!

I recommend you using a template system which renders a html page based in a parametric input to the template code. This input might contain any kind of string or integer so your html code shows the inputs you send.

In your case the input could be the joke, and the joke title, for example.

You don't really need server-side code for this task. So you could use js templates as handlebars , underscorejs or mustache , there are many other approaches out there:

http://handlebarsjs.com/

https://mustache.github.io/

Good luck!

<?php
    $jokes_file = getcwd() . "/jokes.txt";
    $jokes = preg_split('/\r\n|\n|\r/', trim(file_get_contents($jokes_file)));

    $joke_num = rand(0, count($jokes)-1);
    $joke = $jokes[$joke_num];

    print $joke;
?>

getcwd() = get current working directory (for absolute file paths)

preg_split explode the jokes file by newline and turns it into an array.

we get a random joke number, and do -1 as arrays start from 0.

We get a random joke using said number, and then print it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM