How to use SWI Prolog's http/html_write library to write HTML to a file

Viewed 106

I am trying to generate a HTML file using SWI Prolog's library(http/html_write). I would like to produce the HTML below and write it to a file named "mypage.html":

<!DOCTYPE html>
<html>
  <head>
    <title>Hello</title>
  </head>
  <body>
    <h1>Hello</h1>
    <p id="my-id">This is a paragraph.</p>
  </body>
</html>

So far, I have written a Prolog representation of the HTML:

html(head(title('Hello')),
     body([h1('Hello'),
           p(id('my-id'), 'This is a paragraph.')]))

Now what? How do I actually convert this representation into a string which I would then write to a file named "mypage.html"? I have read the documentation (Examples for using the HTML write library), but I am unable to understand how to convert a HTML representation into a string.

I tried to use html_write:print_html/1, but all it does is print the structure like I have written it:

$ swipl --quiet                        
?- use_module(library(http/html_write)).
true.

?- print_html([html(head(title('Hello')),
|                   body([h1('Hello'),
|                         p(id('my-id'), 'This is a paragraph.')]))]).
html(head(title(Hello)),body([h1(Hello),p(id(my-id),This is a paragraph.)]))
true.

?- 

Could you provide a minimal working example for converting a Prolog representation of HTML into a string that is then written to a file?


Update: I have cross-posted this question and received a reply on SWi Prolog's forum: How to use the http/html_write library to write HTML to a file

1 Answers

Your code already writes a string. To write it to a stream mapped to a file, just use this print_html(+Stream, +List).

Maybe you want a minimal working example of a website using html that responds to http://localhost:8080/hello_world

:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/html_write)).
:- http_handler(root(hello_world), say_hi, []).
:- http_server(http_dispatch, [port(8080)]).

say_hi(_Request) :-
        reply_html_page(title('Hello World'),
                        [ h1('Hello World'),
                          p(['This example demonstrates generating HTML ',
                             'messages from Prolog'
                            ])
                        ]).

Consult this file and point your browser to given URI.

Related