1
votes

This is my first question here, so please excuse mistakes.

I want to generate dynamic HTML from a list in Prolog. For each question I want to generate a p-tag with this question.

question(1, 'First Question').
question(2, 'Second Question').

get_quest( Q ) :- question( _, Q ).

index(_Request) :-
  get_quest( Q ),
  reply_html_page(
    [
      title('Dynamic HTML') 
    ],
    [
      h1('Questions'),
      p( Q )
    ]
    ).

I know this can't work, but I can't find the right solution.

UPDATE

here is my implementation of the code. thank you all for help

:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/http_error)).
:- use_module(library(http/html_write)).

server(Port) :-
    http_server( http_dispatch, [ port(Port) ]).

:- http_handler( root(.), index, [] ).
:- encoding( utf8 ).


get_quest( Q ) :- question( _, Q ).

index(_Request) :-
  reply_html_page(
    [
      title('Questions') 
    ],
    [
      h1('Dynamic HTML')
      |\tables
    ]
    ).

tables --> 
  { tables( Ls ) },
  html( [ div( ul( Ls ) )]).

tables( Ls ) :-
  findall( li( Q ), get_quest( Q ), Ls ).
1
Which Prolog are you using? SWI-Prolog has extensive libraries for web development, including html generaton. - user1812457
Hi Boris. Yes, I'm using SWI Prolog. And yes, there are librarys for html generation. But i could't figured out, how to solve this specific problem. It will be something with DCG. @andi thank you for formating my code. - HexXx

1 Answers

1
votes

I was just debugging some bit with this... I assume you have setup the required infrastructure

...
:- use_module(library(http/html_write)).
:- http_handler(/, hello_world, []).
...

hello_world(Request) :-
    debug(wn_basic_gui, '~w', hello_world(Request)),
    reply_html_page([\header, \jquery, \css_binding],
        [\intro
        ,\tables
        ,\footer
        ,\folding_compound
        ]).

tables --> {tables(Ls)},
    html([p(ul(Ls))]).

tables(Ls) :-
    findall(li(\term(S,[])), schema_wn3_table(_,S), Ls).

tables/1 creates the nested <li></li> elements.

For your case, should be easy as

index(_Request) :-
  findall(p(Q), get_quest( Q ), Qs),
  reply_html_page(
    [
      title('Dynamic HTML') 
    ],
    [
      h1('Questions')|Qs
    ]
    ).

here is the 'completed', tested code...

:- module(so, [so/0]).

:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/html_write)).

:- http_handler(/, index, []).
so :- http_server(http_dispatch, [port(1234)]).

question(1, 'First Question').
question(2, 'Second Question').

get_quest( Q ) :- question( _, Q ).

index(_Request) :-
  findall(p(Q), get_quest( Q ), Qs),
  reply_html_page(
    [
      title('Dynamic HTML')
    ],
    [
      h1('Questions')|Qs
    ]
    ).