/
web.txt
2317 lines (1543 loc) · 87.6 KB
/
web.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Tutorial -- Creating Web Applications in SWI-Prolog
===================================================
Anne Ogborn <annie66us@yahoo.com>
:Author Initials: AO
:Revision: 1.2.2
:Revision: 1.2.2
:Date: Dec 20, 2015
:toc2:
:icons:
:numbered:
:website: http://www.pathwayslms.com/swipltuts/
:theme: pathways
link:/swipltuts/index.html[Up to All Tutorials]
This tutorial updated {date}
Introduction
------------
Expected Results
~~~~~~~~~~~~~~~~
If you enter this course knowing SWI-Prolog well and have some experience with web development, you should be able to competently write production web applications afterwards. The learning curve is pleasantly short.
Time
~~~~
3-6 hours if you do all the exercises. You can start writing 'real' code after finishing section 3 at minimum.
Who This Course Is For
~~~~~~~~~~~~~~~~~~~~~~
This course is for anyone who knows SWI-Prolog reasonably well and wants to learn the web application framework bundled with SWI-Prolog. You will also need some fluency with web development basics like HTML, CSS, and HTTP.
Many programmers assume Prolog needs to be hosted with a 'normal' language. I'm not sure why. Certainly xpce wouldn't be suitable for many desktop gui systems. But those are becoming rare. Even the desktop systems I've written recently have been written as web servers that display the UI in the browser. This course is part of my response to this mentality.
Why Prolog?
~~~~~~~~~~~
Prolog is of course more associated with expert systems and torturing undergraduates than with production web applications. But I've found it an excellent system for building web applications as well.
Prolog programs are simply *smaller* . Prolog programs are often *one tenth* the size of equivalent Java programs. And smallness is a virtuous cycle. Smallness encourages well written code, and well written code is easier to maintain and refactor and remains small.
What makes Prolog systems small? Complex question, but we can identify various factors. With backtracking instead of control structures, Prolog eliminates the 90% of loops that are actually iterators. Backtracking often eliminates error handling. Partial binding and incomplete structures eliminate much data reformatting. And in general, there's just a lot more case based reasoning, which means a lot less ceremony associated with handling of edge conditions. And of course you can put a small reasoner in to figure out complex business logic like 'who's allowed to edit this?'
The SWI-Prolog web app framework is very friendly. You can edit running code and query make. (C-c C-m in the IDE editor) and keep going without disturbing state, and you can use the graphic debugger.
Does Anybody Actually Use This?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All these systems are in Prolog, using the web framework described in this tutorial.
image:systemsusingprolog.png[The best way to be cool and ahead of the curve is by asking if large companies are using the technology before you try it]
Getting The Most From This Course
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This course is this web page and a series of example programs.
The examples are designed to take reasonable sized bites at a subject, progressively building knowledge. I introduce some subjects in one place, then revisit them later to deepen understanding.
The example programs are *not* reproduced here. I want you to actually *look at* and *fiddle with* the code. So hopefully you'll be encouraged to fiddle if you have to read the code locally. You can get the examples at https://github.com/Anniepoo/swiplwebtut
To get the most from this course, you'll need to
* Have a working http://www.swi-prolog.org[swi-Prolog] install
* Get the example files from https://github.com/Anniepoo/swiplwebtut[github]
* Understand Prolog and SWI-Prolog's dialect before trying to build web apps
* Read the text
* Try each example program. Especially, look at the source of the resulting page. Experiment!
* Do the exercises
The example programs are labelled with a number scheme that once aligned with the chapter and section number, so webserver1_2.pl was the code for chapter one section 2. They've long since drifted out of alignment, and I've just put the number in the heading.
Different people will have different backgrounds and learning styles. Whatever works for you works.
http://www.swi-prolog.org/howto/http/'[This page] in the SWI-Prolog docs is useful as well
Getting Stuck
^^^^^^^^^^^^^
Many of the exercises in this tutorial were designed to push you to go explore the documentation. I feel students learn more from doing tasks like 'real programmers', and 'how do I do X' is a daily experience for all of us. So don't assume you can do all the exercises from this document! You can't!
If you have questions and reasonable effort doesn't answer them, drop me email at annie@theelginworks.com . Please, if you're taking a beginning Prolog course, ask your instructor basic Prolog questions. Questions about family trees will be ignored. But if you're working on a web app, feel free.
Asking on ##Prolog on freenode.net is also a good way to get answers.
Finally, I well could be wrong. This material's not that well documented in spots, and I'm making these tutorials partly to teach myself. While the web app *feels* nice to handle, in practice I've had a frustrating number of wtf moments. I'm hoping this tutorial will help change that.
Learning By Doing
^^^^^^^^^^^^^^^^^
The only way to really become competent with an API is to use it. So, just as much as exercises or this page, I encourage you to make a project with the SWI tools. At the end of the course there's a plea for people to help with a library of web patterns. If you don't have a specific project, you might consider doing that.
If you're the "dive in and figure it out, make a toy project" sort, you may want to peek ahead to the parameters section at some point, as the course order slogs through all of html generation first, an orderly process but one that means you're limited what you can build til you get there.
With all that out of the way, on to the tutorial.
Setting Up Handlers
-------------------
Hello Web
~~~~~~~~~
.Hello Web example
[NOTE]
=====
See file helloweb.pl
=====
(Like always, I'm assuming you're reading the code in the SWI-Prolog IDE, so I'm not showing the code here).
Web apps in SWI-Prolog can be run in various ways. The one we'll use to start is simply running as our own web server. I'm going to cover the larger issues later, so for now I'll give you a bit of voodoo code to get a basic server up and running
These lines include modules needed for our basic server
----
:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
----
And this is our main server loop.
----
server(Port) :-
http_server(http_dispatch, [port(Port)]).
----
Query +server(8000).+ to start the server on port 8000 and browse http://127.0.0.1:8000/
****
Exercise
Run helloweb.pl, start the server, and look at result in browser
****
Handlers
~~~~~~~~
SWI-Prolog web apps are defined as a collection of *handlers* . The first topic we'll cover is defining handlers. If you know Ruby on Rails these are like 'routes'.
We have a single handler that handles the root path /
----
:- http_handler(/, say_hi, []).
----
This declaration says 'handle the root of the tree by querying the goal say_hi.'
The first argument, /, is an atom that means 'the root of the URI'. So if we instead wanted our server to serve http://127.0.0.1:8000/twinkly/elf/weenblat.xls we'd say
----
:- http_handler('/twinkly/elf/weenblat.xls', say_hi, []).
----
****
Exercise
serve Hello World from http://localhost:8000/hello.txt
Exercise (harder)
serve Hello World from any URI under http://localhost:8000/
****
The second argument will be called with +call(Arg, Request)+, where Request is the request info. This enables the handy trick of making similar handlers into a single pred with specialization, like this:
----
:- http_handler('/something/pleasant', my_handler_code(pleasant), []).
:- http_handler('/something/painful', my_handler_code(painful(normal)), []).
:- http_handler('/something/very/painful', my_handler_code(painful(very)), []).
:- http_handler('/something/incredibly/painful',
my_handler_code(painful(incredibly)), []).
my_handler_code(WhatToSay, Request) :-
in here WhatToSay will be bound to pleasant, painful(normal),
painful(very), or painful(incredibly)
and Request is a complex term that represents the httprequest (covered later)
----
The last argument is a set of options. The most interesting of these is +prefix+, which lets a single handler handle everything below the route as well. If you need to override an existing handler, you may need the priority option. +priority(0)+ is default.
Now we're ready for the actual handler rule.
When the rule is called the current input stream has been redirected to read the HTTPRequest, and current output has been redirected out the socket, so all we need do is print the response.
We'll first write the required Content-type: header and then the body.
----
say_hi(_Request) :-
format('Content-type: text/plain~n~n'),
format('Hello World!~n').
----
Don't worry, this is NOT the usual way of writing content. But that's chapter 2!
.Different hello messages
****
Exercise:
Add handlers to helloweb.pl that print two different hello messages and share a single handler rule.
Exercise (harder):
serve up a small png image just using format calls
Exercise:
Add the Server: header to the response, using +version/1+ to get the SWI-Prolog version of your SWI-Prolog install.
The header should look something like
Server: Apache/2.4.1 (Unix)
****
Abstract Paths
~~~~~~~~~~~~~~
.Abstract Path example
[NOTE]
=====
See file abstract_path.pl
=====
Anyone who'se made a large web app will be worried by the way we've been encoding our HTTP paths. '/fluffybunny' is fine for a small website, but imagine maintaining a large system with all these absolute paths hard coded.
WARNING: If you're used to Apache based systems you probably associate an URI path with a file path. e.g. this tutorial will be found at http://www.pathwayslms.com/swipltuts/html/index.html . But it's served by sending the contents of a file, index.html, at /var/www/swipltuts/index.html on my server. The first is an URI path, the second a file path. They're different!
The solution is what SWI-Prolog calls 'abstract paths'.
The abstract path library is at http://www.swi-prolog.org/pldoc/doc/swi/library/http/http_path.pl if you want the gory details.
In example abstract_path.pl our handler declarations have changed. They now look like
----
:- http_handler(root(.), say_hi, []).
% And, just for clarity, define a second handler
% this one can by reached at http://127.0.0.1:8000/taco
:- http_handler(root(taco), say_taco, []).
----
The first is our old friend, the root handler, which serves http://127.0.0.1:8000/
Paths are offsets from an abstract base. In our case, the only abstract base is the built in one, root, which is defined as /.
So / is root(.), /taco is root(taco), and +root('foo/bar')+ is /foo/bar (note, not +root(foo(bar))+).
You're probably thinking, other than syntactic change, so what?
On to
Defining new abstract paths
~~~~~~~~~~~~~~~~~~~~~~~~~~~
.New Abstract Path example
[NOTE]
=====
See file new_abstract_path.pl
=====
The example new_abstract_path.pl code adds a hook predicate that defines a new abstract path. With it, we can now say files('zap.gif') to serve /f/zap.gif. If we move the files somewhere else we can just change one line.
IMPORTANT: The path to the root of *files* (second arg) is an absolute path specification, not root(.)
----
:- multifile http:location/3.
:- dynamic http:location/3.
http:location(files, '/f', []).
----
Also notice that +location+ is arity 3. It takes a list of options, the only valid option being +priority(+:integer)+ which is used to disambiguate multiple handlers that handle the same URI. This is useful for defining a fallback handler for prefix of / to make a custom 'not found' page instead of 404ing, and for overriding portions of the URI space.
IMPORTANT: I was tryig to make these 'abstract paths' be abstract files paths for a long time when learning this stuff. Beware, the two have nothing to do with each other. To make things worse, later on we'll encounter them used together.
.sorry, not here exercise
****
EXERCISE:
create a new abstract path /food/ and move taco to be under it
EXERCISE:
Abstract URI paths really only become useful as a website grows, and things need moved around.
Extend the previous exercise to have /food/mexican/, /food/french/, /food/japanese/ and serve an example food for each one.
Arrange your code so the paths can be changed to /cuisine/mexican/, /cuisine/french/, and /cuisine/japanese/ by changing a single http:location definition.
Hint, use +http_absolute_uri/2+
EXERCISE:
Move a handler, use the make command, then try to access the old location. It may work until you restart.
Lesson learned - restart after you muck with location.
****
Moving the whole shebang
~~~~~~~~~~~~~~~~~~~~~~~~
Your server will some day probably be proxied to by apache, so your root path may be changed. You can change all abstract paths at once by redefining the setting http:prefix.
****
Exercise
Change the setting and confirm it works
Question
Does it still serve at the old location?
****
File Path Aliases
~~~~~~~~~~~~~~~~~~~
SWI-Prolog has an abstract file path system - you've seen it when you include modules with
----
:- use_module(library(http/html_write)).
----
+library+ is an abstract file path, also known as a _path alias_.
Various places in the web framework refer to files, so I'm covering this material now.
Just as hard coded URI's become painful as a site grows larger, hard coded file paths become painful.
Developers can define additional file search paths. For example, you might have a project flubbercalc you bring into your project as a git submodule. You'd like to have those files look like part of the available libraries.
Add a clause to the multifile predicate +user:file_search_path/2+ for it.
----
user:file_search_path(library, './flubbercalc').
----
You can also add your own paths. Say you have a file of videos you serve.
----
user:file_search_path(videos, './videos').
----
Unlike URI locations, path aliases can be defined in terms of other aliases
----
user:file_search_path(videos, './videos').
user:file_search_path(kiddy, videos(children)).
----
Say you have two sources of kiddy videos you purchased from different distributors, movietime and moviola. For some purposes you need them separate, but you want to be able to refer to all of them as if they're in one directory at times.
----
user:file_search_path(videos, './videos').
user:file_search_path(kiddy, videos(children/movietime)).
user:file_search_path(kiddy, videos(children/moviola)).
----
If this system is being your enemy instead of your friend, you can debug with the Prolog flag verbose_file_search. Setting it to true makes the system print out the absolute paths each time it resolves a file name. You can also directly query expand_file_search_path and see all the matches of a spec.
Generating HTML
---------------
So far we've served plain text. Lets serve HTML.
This is the longest chapter in the tutorial. I'm approaching it from the bottom up, so don't panic until we cover +html//1+ if the HTML generation looks ugly.
Two Camps
~~~~~~~~~
There are two camps when it comes to HTML generation.
image:twocamps-01.png["Well, for Prolog there are three camps - us unemployed, broke, homeless Prolog programmers have our own camp down by the railroad tracks"]
The 'template' camp wants to edit HTML with normal HTML tools, and will live with awkward php/jsp/asp style +<% .... %>+ escaping for dynamic generation.
The dynamic camp wants to dynamically generate web pages, and will live with an idiomatic 'funny looking' HTML representation for the convenience of mixing code and HTML easily.
Options
^^^^^^^
In SWI-Prolog you have several options:
simple-template::
Simple-template by Raivo Laanemets (installable as a pack, or at https://github.com/rla/simple-template ) enforces the strictest separation of logic and formatting. Simple-template doesn't allow prolog code in the template.
Prolog Web Pages::
PWP is the most asp/jsp like, with the advantage that it's well formed XML. http://www.cs.otago.ac.nz/staffpriv/ok/pwp.pl
+html//1+::
Prolog syntax DCG based HTML generation. Part of the SWI-Prolog distribution.
This chapter is about the built in SWI-Prolog HTML generation support using +html//1+, which is firmly in the 'dynamic' camp. PWP and Raivo's simple-template systems both have excellent documentation. I see no point in repeating them here.
If you pitch your tent in the template camp, SWI-Prolog provides support for it http://www.swi-prolog.org/pldoc/doc_for?object=section%283,%273.21%27,swi%28%27/doc/packages/http.html%27%29%29[integrating PWP] .
But both sides of the debate have merit. Templates are great for working with a web designer, and of course the toolchain for normal HTML is far better developed. Separating function and appearance is a good thing to do, especially if you'll be using the code for more than one website.
On the other hand, modern web applications seem to make almost everything on the page dynamic. On the SWI-Prolog.org website, for example, even Owlie the owl icon is dynamic (he changes on holidays). If you're generating tiny bits of HTML automatically, templates can become a nightmare.
TIP: As an aside, if you like the whole WordPress style 'they write most of the application for me' framework, check out Raivo Laanemets' http://blog-core.net/[Blog-Core].
Combining Options
^^^^^^^^^^^^^^^^^
Fortunately, this is a false dicotomy. It's easy to integrate the systems.
That said, you can indeed output a block of 'normal' HTML with the built-in support. Some strategies for doing so (skipping ahead a bit):
* Use the html quasiquoter. You can write some normal HTML and say to SWI-Prolog 'turn this stuff into your dynamic representation'.
* Include bits of 'normal' HTML in an otherwise dynamic page by using the inclusion mechanism described under 'inclusion' in 2_6
* Serve entire static pages (eg. a terms of service page) using the file serving mechanisms described in 6_1
* Use print_html/1 to generate tokenized HTML dynamically, then insert it in simple-template using +{{- expression }}+
Directly printing HTML
~~~~~~~~~~~~~~~~~~~~~~
.Direct Printing example
[NOTE]
=====
See file direct_print.pl
=====
We can serve HTML just by printing it.
----
say_hi(_Request) :-
format('Content-type: text/html~n~n'),
format('<html><head><title>Howdy</title></head><body><h2>A Simple Web Page</h2><p>With some text.</p></body></html>~n').
----
Ouch!
Clearly we're not doing this for long. But it's nice to know you can just print if the handy helper stuff is fighting you.
Using print_html
~~~~~~~~~~~~~~~~
.Using print_html example
[NOTE]
=====
See file print_html_example.pl
=====
This isn't any better, but is an important step in understanding.
WARNING: *Don't* do this in your own code.
+print_html+ is a behind the scenes predicate that converts a list of HTML chunks into a string containing HTML. Besides just concatenating, it inserts some rough formatting.
----
say_hi(_Request) :-
format('Content-type: text/html~n~n'),
print_html(
['<html>',
'<head>',
'<title>',
'Howdy',
'</title>',
'</head>',
'<body>',
'<h2>',
'A Simple Web Page',
'</h2>',
'<p>',
'With some text.',
'</p>',
'</body>',
'</html>']).
----
Representing HTML
~~~~~~~~~~~~~~~~~
SWI-Prolog has 3 representations for HTML. It can be a single atom, like in 2_1, or a list of tokens, (tokenized html), or a term form (termerized html) that we'll show next. Keeping track of which form you're working with can be one of the more confusing bits. So I'm introducing some terminology that Jan doesn't use in the SWI-Prolog documentation.
*HTML atom*::
an atom or string with HTML in it (the 2_1 representation)
*Tokenized HTML*::
The stuff above
*Termerized HTML*::
The stuff we'll show in 2_3
.Look at output
****
EXERCISE:
Run print_html_example and look at the generated HTML.
****
html//1 And Termerized HTML
~~~~~~~~~~~~~~~~~~~~~~~~~~~
.HTML DCG example
[NOTE]
=====
See file html_dcg_example.pl
=====
The primary tool for generating HTML in real applications is +html//1+, a DCG that takes an argument that defines some html using a domain specific language we call _Termerized HTML_.
image:comfy.png["He's just read my DCG tutorial, that's why he looks like that", width=244,link="/swipltuts/clpfd/clpfd.html"]
Finally, we see something that looks like reasonable HTML generation.
Web pages are nested structures of boxes within boxes and areas on a page. While they have a strong structural similarity to their HTML representation, they are not identical. A search box is not, conceptually, just a text field, but is a thing unto itself.
Representing the _page's_ structure and converting it to a list of HTML chunks is list generation, and there's a natural tool in Prolog for list generation - the DCG.
That's what SWI-Prolog does, in a sorta sideways way. Here's an example:
----
phrase(
html(
[head(title('Howdy')),
body([h1('A Simple Web Page'),
p('With some text')])
]),
TokenizedHtml,
[]),
----
Notice that we're using +phrase/2+. +phrase+'s first argument is a library DCG, +html//1+, whose argument is a DSL (domain specific language) which defines the HTML it recognizes. So, phrase/2 will unify in the above when +TokenizedHtml+ is the tokenized HTML equivalent of the red stuff, the 'termerized HTML' defined by the first arg of +html//1+.
It is this DSL which is our 'termerized HTML'.
Proving it's a real DSL
~~~~~~~~~~~~~~~~~~~~~~~
.Real DCG example
[NOTE]
=====
See file real_dcg.pl
=====
Using a DCG just to call +html//1+ and passing it the termerized HTML probably seems, at this point, pretty Rube Goldberg-ish. When we get to inclusions you'll see why it's done.
Lets prove that it's a real DCG by abstracting out the generation into it's own nonterminal (See the file).
----
say_hi(_Request) :-
phrase(
my_nonterm,
TokenizedHtml,
[]),
format('Content-type: text/html~n~n'),
print_html(TokenizedHtml).
my_nonterm -->
html([html([head([title('Howdy')]),
body([h1('A Simple Web Page'),
p('With some text')])])]).
----
reply_html_page
~~~~~~~~~~~~~~~
.+reply_html_page+ example
[NOTE]
=====
See file reply_html_page_example.pl
=====
Generating our own head and body tags is more ceremony than we really need. SWI-Prolog provides a nice wrapper that takes care of the boilerplate, and in the process handles a lot of other behind the scenes work. Notice it's handled the Content-type header for us.
----
say_hi(_Request) :-
reply_html_page(
[title('Howdy')],
[h1('A Simple Web Page'),
p('With some text')]).
----
We're down to a single API call that takes some termerized HTML to include in the head and the contents of the body, which is pretty close to zero ceremony.
(If you're paniced and thinking 'oh, man, I don't control the head?', relax - you do, we'll get there when we cover the arity 3 version +reply_html_page/3+ in a bit.)
Termerized HTML Syntax
~~~~~~~~~~~~~~~~~~~~~~
.+termerized_html+ example
[NOTE]
=====
See file termerized_example.pl
=====
Now we're ready to look at the termerized HTML syntax. You'll definitely want to have termerized_example.pl open in front of you as you read this.
The SWI-Prolog docs for this are in http://www.swi-prolog.org/pldoc/doc_for?object=section%283,%273.17%27,swi%28%27/doc/packages/http.html%27%29%29[this location] (which I recommend bookmarking, as finding it is always exciting).
Termerized HTML uses an arity 1 or 2 term for each HTML tag.
The arg of arity 1 terms is the innerHTML. The args of arity 2 terms are attributes and innerHTML. Either one can be a list to allow multiple items.
----
say_hi(_Request) :-
reply_html_page(
[title('Howdy')],
[
h1('A Simple Web Page'), % arity 1
p(class=bodytext, 'With some text'), % arity 2
p([class=bodytext, style='font-size: 120%'], ['Bigger text', b('some bold')])
]).
----
The html//1 term takes a term or a list as it's sole argument, in the same format at the innerHTML argument of tag term
Here's most of the forms you can apply:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
CAUTION: One form you *won't* see is a nested list. +[p('a para'), [p('in a nested list')]]+ is *not* valid termerized HTML. You've been warned.
Inner HTML
^^^^^^^^^^
A simple headline with plain text inside it
----
h1('A Simple Web Page'),
----
A bold paragraph
----
p(b('some bold text'))
----
If it's a list, the items are converted individually and concatenated.
A div block with two paragraphs
----
div([p('a para'), p('another para')])
----
Entities
^^^^^^^^
entity escaping happens
----
p('<b>this wont be bold</b>')
----
appears literally, not in bold.
If you need an entity you can name one
----
&(copy)
----
gives a copyright symbol
----
p(['Copyright ', &(copy), ' 2012, Anne Ogborn'])
----
String Help
^^^^^^^^^^^
There's much help to perform string operations. You can get +format/2+ style formatting using -
----
p('these ~d things, faith, hope, and love. But the greatest of them is ~w'-[3,love])
----
Concatenation usually isn't needed, but is +
----
p('two strings'+'two strings')
----
would usually be expressed
----
p(['two strings', 'two strings')
----
Though the first doesn't leave a space between them
Attributes
^^^^^^^^^^
This paragraph has a style and tooltip text.
----
p([style='font-size: 36pt', title='tooltip text'], 'With some text'),
----
If there's a single attribute the list can be omitted
----
p(class=foo, 'some text')
----
Notice that SWI-Prolog will put the quotes around foo in the HTML. As always in Prolog you have to quote atoms with iffy chars in them, like the src and alt attributes below.
----
img([src='obama.png', class=pres, height=128, width=128, alt='Barack Hussain Obama'], [])
----
Attributes have an even more extensive set of helper operators.
Attributes can be specified by K=V pairs like +class=foo+ or by K(V) terms like +class(foo)+. The latter form is useful for avoiding operator priority worries
Concatenate like this:
----
class=alert+AlertLevel
----
Format strings like +format/2+ go like this:
----
alt='Image of ~w'-[Subject]
----
+List produces a query string with proper urlencoding
----
href='mep.php?'+[name=Name, email=Email, sex=Sex]
----
This urlencodes an arbitrary atom or string
----
href='http://example.com/foo.php?msg='+encode(MyMessage)
----
Later we'll cover another way of specifying a handler, by ID. This syntax creates a URL from a location ID.
----
href=location_by_id(ID) % treated later
----
A list not interpretable as right side of operator is joined with spaces. This is useful for multiple class lists.
----
class=[emphasize, left, question]
----
becomes
----
class="emphasize left question"
----
This bit about namespaces is slightly esoteric, feel free to skip down to the next exercises if not of interest.
Attributes in other namespaces look like this. This is fairly rare in html, it shows up when mixing in XML or RDF related stuff. Here we have elgin:advisory. Note that, surprisingly, HTML5 doesn't "know" about namespaces, and adding them to the html tag is invalid. Colon is a normal character in attributes in HTML5.
----
html(div([class(Classes), elgin:advisory(ToolSet)],
[img([class('el-tool-image'), elgin:advisory(ToolSet), alt(Alt), title(Alt), src(Image)]),
\subtools(ToolSet)]
)).
----
If you're in XHTML dialect you can add namespaces with +xhtml_ns//2+. By default SWI-Prolog puts out HTML5. To put out XHTML do
----
html_set_options([dialect(xhtml)])
----
This section's certainly long, but it's the core of the tutorial. Still, lets break and do a few exercises to absorb what we've learned.
.html exercises
****
Exercise:
Convert a simple web page from a project you've made into termerized HTML.
Build your own example of each element in this section
****
Inclusion
---------
.+termerized_html+ example
[NOTE]
=====
This section also uses file termerized_example.pl
=====
HTML is a markup language. It's tags are not the semantic units of a web page as we think about it. We want to talk about the login box, not a div with a text box blah blah. Inclusion is SWI-Prolog's mechanism for encapsulating HTML generation code. This means you can create structured, reusable components of web pages, and pays off many times the slight awkwardness of 'funny looking html'.
Inclusion is signaled by +\+. If the argument of \ is a term, it will be treated as a DCG, and expanded to tokenized HTML.
The line
----
\some_included_stuff,
----
Calls the DCG
----
some_included_stuff -->
html([p('Some included stuff')]).
----
Of course you can pass semantic arguments
----
\more_included_stuff('Whoop Whoop!'),
----
...which calls...
----
more_included_stuff(X) -->
html([p(['More included stuff: ', b(X)])]).
----
Notice you're back in tokenized HTML space (and in Prolog). You need +html//1+ here.
You only need +html//1+ when it's time to make literal HTML. Nothing wrong with
----
included_stuff(X) -->
another_inclusion(X),
and_a_third_inclusion(X).
----
Included lists are treated as literal, tokenized HTML to be included. So, you can include a block of HTML set up with a normal editor
----
\['<i>in italic</i>', '<b>now we have bold</b>'],
----
WARNING: If you do this you can't depend on +html//1+ always producing valid HTML. For this reason, seriously consider using quasiquotes instead. Quasiquotes largely deprecate this mechanism.
CAUTION: The list brackets for including a literal are not optional! +\[term]+ and +\term+ are completely different. The first puts <i>term</i> in the html. The second treats term as an inclusion.
A useful way of thinking about inclusion is that \ is an escape that says, in effect 'enter tokenized HTML world'. \
Inclusion is simultaneously one of the neatest features of SWI-Prolog web, and one of the greatest sources of frustrating bugs.
The secrets to avoid driving yourself insane with inclusion are, first, understand whether you're in termerized HTML or tokenized HTML space. Second, be aware you aren't in prolog, and need to follow the DSL's, not Prolog's, module rules.
Quasiquotes
~~~~~~~~~~~
.Quasiquotes example
[NOTE]
=====
This section uses file quasiquotes_example.pl
=====
At this point those of you in the template camp are probably running in circles, screaming and shouting, thinking that the only escape from Jan's strange formatting for html is to abandon ship and use simple-template, or ignore the warnings liberally plastered about the +\[ ]+ format.
Have no fear, quasiquotes are here.
Quasiquotes are an extension to the Prolog syntax that says, effectively *"and now for a little of this other language, which I'll syntax check and convert at compile time to a Prolog term"*.
Here's demo of the html quasiquoter in use. We import html_write to get the appropriate quasiquoter (html in this case) and then use +{|html(Y)||<p>Y</p>|}+, the curly brackets and or bars defining "this is a quasiquoter, here's the args and body". +html(Y)+ defines the args to be passed in (notice that it's not like function argument passing, the name can't be changed like with a formal arg on a function), and inside is the body, which is syntax checked, and Y is replaced.
----
2 ?- use_module(library(http/html_write)).
true.
3 ?- Y=7,X = {|html(Y)||<p>Y</p>|}.
Y = 7,
X = [element(p, [], [7])].
4 ?-
----
Just the thing for us. Now we have syntax checking, editor coloring, and aren't in the wild west of converting between html and strings.
Here's what it looks like inside of a DCG inclusion:
----
my_headline(X) -->
html({|html(X)||<h1>X</h1>|}).
----
Notice we've passed it to +html//1+. That's usually what you'll do with it.
But what's it compile into?
The SWI-Prolog docs say
.+html/4+ Quasiquote output format
____
These quotations produce a DOM term that is suitable for html//1 and other predicates that are declared to consume this format.
____
-----
?- use_module(library(http/html_write)).
true.
4 ?- X = hello,Y = {|html(X)||<h1>X</h1>|}.
X = hello,
Y = [element(h1, [], [hello])].
5 ?- Y = {|html(X)||<h1>X</h1>|}.
Y = [element(h1, [], [X])].
-----
The funny list with element/3 term in it is the format SWI-Prolog represents SGML in. But usually you won't care about that.
If you want to insert some normal HTML boilerplate in the midst of a mass of termerized html, do it like this:
----
my_inclusion(X) -->
html([
p('termerized para'),
\html({|html(X)||<p>X</p>|})
]).
----
Admittedly slightly verbose.
Inclusion And Modules
~~~~~~~~~~~~~~~~~~~~~
.Inclusion and Modules Example
[NOTE]
=====
This section also uses file termerized_example.pl and anothermodule.pl
=====
image:comfymodule-01.png["His coffee's gone cold",width=244]
Now that you can make nifty bits of pages, you start accumulating them and soon you have enough you need to organize into modules. You use the usual use_module system and life is good for a while.
Then you get this bright idea. You could make your site look really awesome by using Javascript and HTML5 to draw a 'hand drawn' border around the various sections. But now we want to add the 'hand drawn' look without having a mess everywhere. We could do:
----
start_hand_drawn_box, ... contents, \end_hand_drawn_box
----
but that's ugly - it doesn't express the containment structure.
So we write an inclusion DCG that takes some termerized html as an argument and adds the html around it to make the hand drawn look.
----
hand_drawn_box(InnerHTML) -->
html([.... whole bunch of crazy javascript stuff...,
div(class=hand, InnerHTML),
... more totally unreadable javascript ... ]).
----
We try this, and, after debugging the ugly javascript, it works. Cool! So, being organized, we move it into it's own module. And suddenly it fails when we try this:
----
%in module1
email_me_form -->
html([div(class=emailme, form(.... mass of form code ...))]).
my_contents -->
html([... stuff...,
\hand_drawn_box([... stuff..., \email_me_form, ...]),
... endless stuff ...]).
%in module2
hand_drawn_box(InnerHTML) -->
html([.... whole bunch of crazy javascript stuff...,
div(class=hand, InnerHTML),
... more totally unreadable javascript ... ]).
----
And it complains it doesn't know about module2:email_me_form//0 - Ooops! hand_drawn_box is binding it's arguments at the wrong time!
The same thing can happen in 'normal' Prolog code. The fix there is the +meta_predicate/1+ declaration, which marks which arguments are 'module sensitive'. Module sensitive arguments have their module resolved before the call. Unfortunately, we're not in Prolog, we're in termerized HTML DSL language.
Fortunately there's an extension to meta_predicate that handles html. +html_meta+ works like meta_predicate, but allows html as well as the usual :, ?, +, -, etc. At compile time, the termerized HTML gets module extended in the context of the caller, and Bob's yer uncle.
Now we can make an inclusion that takes html:
----
%in module2
:- html_meta hand_drawn_box(html,?,?).
hand_drawn_box(InnerHTML) -->
html([.... whole bunch of crazy javascript stuff...,
div(class=hand, InnerHTML),
... more totally unreadable javascript ... ]).
----
+hand_drawn_box+ takes termerized HTML as it's first argument. Remember that it's a DCG, so there are two additional arguments for the difference list, hance the two ? arguments.
Besides fixing the module issue, the pceEmacs editor will now properly syntax color the argument.
This works great as long as you're passing termerized html around. Imagine things are even worse - say you're passing a list containing various html hunks to an inclusion, and it's supposed to include one based on some other criteria. We can't use +html_meta/1+.
The solution is to explicitly specify the module of the inclusions. Remember, you're *not in Prolog*, but *in the DSL*, so you have to use the DSL's module rules. So you'll need to do this for inclusions from the calling module, not just from other modules.
----
\(othermodule:inclusion(X))
----
Operator precedence makes the parens necessary.
I would say, module issues are, along with inclusion, the great pain points in using the web framework. Don't go past this point without understanding the module system, +meta_predicate+, +meta_html+, and how inclusion works.
Start A Project
^^^^^^^^^^^^^^^
At this point our exercises start building on each other. You may want to copy one of the examples to create a starting point.
****
Exercise: Create a simple web page with a form that does a GET to gather a message. You needn't build anything to handle the form.
Exercise: Encapsulate the form in a separate DCG so it can be reused.
Exercise: Create a DCG motd//0 that shows the MOTD or other dynamic data as an inclusion. Add it to your page.
Exercise: create a DCG my_fancy_border//1 whose argument is termerized HTML representing what's inside the border. Make it surround the passed HTML with a div with some fancy border. (for now use a style= attribute in the div, since we haven't covered stylesheet inclusion).