├── .github └── workflows │ └── test.yml ├── LICENSE ├── README.md ├── examples └── dice │ ├── Dice.gif │ ├── README.md │ ├── app.pl │ ├── dice.svg │ ├── htmx.min.js │ ├── index.html │ └── lyncex.pl ├── expr.pl ├── expr_tests.lgt ├── filters.pl ├── filters_tests.lgt ├── parser.pl ├── parser_tests.lgt ├── render.pl ├── templates ├── a.in.html ├── a.out.html ├── b.in.html ├── b.out.html ├── base.html ├── c.in.html ├── c.out.html ├── child.html ├── child.out.html ├── child3.html ├── d.in.html ├── d.out.html ├── e.in.html ├── f.in.html ├── footer.html ├── g.in.html ├── grandparent.html ├── h.in.html ├── h.out.html ├── i.in.html ├── issue-4.in.html ├── j.in.html ├── j.out.html └── parent.html ├── teruel.pl ├── tester.lgt └── tests.lgt /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | on: [push] 3 | 4 | jobs: 5 | test: 6 | runs-on: ubuntu-22.04 7 | steps: 8 | - name: Install Rust cargo 9 | uses: actions-rs/toolchain@v1 10 | with: 11 | toolchain: stable 12 | profile: minimal 13 | components: cargo 14 | - name: Checkout 15 | uses: actions/checkout@v3 16 | - name: Checkout Scryer Prolog 17 | uses: actions/checkout@v3 18 | with: 19 | repository: mthom/scryer-prolog 20 | path: scryer-prolog 21 | - name: Compile Scryer Prolog 22 | run: cargo build --release 23 | working-directory: scryer-prolog 24 | - name: Install Scryer Prolog 25 | run: sudo cp scryer-prolog/target/release/scryer-prolog /usr/bin/scryer-prolog 26 | - name: Install Logtalk 27 | uses: logtalk-actions/setup-logtalk@master 28 | with: 29 | logtalk-version: 3.70.0 30 | - name: Execute tests 31 | run: logtalk_tester -p scryer 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Teruel - Template engine for Prolog 2 | 3 | Teruel is a template engine in ISO Prolog, inspired by Tera and Jinja. 4 | 5 | # Installation 6 | 7 | # API Usage 8 | 9 | Load the library: 10 | 11 | ``` 12 | :- use_module('teruel.pl'). 13 | ``` 14 | 15 | The predicate `render/3` will be available for you. 16 | 17 | * `render(+Filename, +Vars, -Output)`. 18 | - Filename. The template path 19 | - Vars. A list of pairs for the variables you want to be available in the template 20 | - Output. The output text after rendering. 21 | 22 | ``` 23 | render("templates/i.in.html", ["username"-"aarroyoc", "links"-["https://github.com", "https://adrianistan.eu"]], Output). 24 | ``` 25 | 26 | If you're using the Scryer HTTP server and you want to render HTML files, you can simplify your code by using the predicate `html_render_response/2,3`. 27 | 28 | * `html_render_response(Response, +Filename, +Vars)`. 29 | - Response. The Scryer HTTP response 30 | - Filename. The template path 31 | - Vars. A list of pairs for the variables you want to be available in the template 32 | 33 | * `html_render_response(Response, +Filename)`. 34 | - Same as `html_render_response/3` but with Vars = []. 35 | 36 | # Manual 37 | 38 | Teruel is a template engine. It takes a text file annotated with some code in delimiters and returns a processed text file (renders it). It is usually used with HTML, but Teruel doesn't make any assumption. 39 | 40 | There are 3 kinds of delimiters: 41 | 42 | * Comments, which do nothing 43 | * Expressions, which calculate a value 44 | * Statements, which allows to control flow 45 | 46 | ## Comments 47 | 48 | Comments use `{#` and `#}`. Text inside comments doesn't get rendered. 49 | 50 | For example: 51 | 52 | ``` 53 | {# TODO: Add users #} 54 | 55 | ``` 56 | 57 | renders: 58 | 59 | ``` 60 | 61 | ``` 62 | 63 | ## Expressions 64 | 65 | Expressions `{{` `}}` are code that evaluate to a value. Also, you can include expressions in some statements like if (see if statement). They can contain variables (which are defined by you, see API Usage) and some operations. However it is not a good idea to create complex expressions in the template, move that logic to your Prolog code. 66 | 67 | The most basic expression is just rendering a variable: 68 | 69 | ``` 70 | Hello {{ name }} 71 | ``` 72 | 73 | renders to (Vars = ["name"-"Adrián"]): 74 | 75 | ``` 76 | Hello Adrián 77 | ``` 78 | 79 | Variables can be: numbers, strings, lists and maps. If you want to access a field on a map use the dot syntax: 80 | 81 | ``` 82 | Hello {{ user.display_name }} 83 | ``` 84 | 85 | renders to (Vars = ["user"-["display_name"-"Adrián"]]) 86 | 87 | ``` 88 | Hello Adrián 89 | ``` 90 | 91 | ### Math in expressions 92 | 93 | If a variable is a number, you can do some math in it. 94 | 95 | * `+` performs sum, `{{ 1 + 1 }}` renders `2` 96 | * `-` performs substraction, `{{ 2 - 1}}` renders `1` 97 | * `/` performs division, `{{ 10 / 2 }}` renders `5` 98 | * `*` performs multiplication, `{{ 2 * 2 }}` renders `4` 99 | * `%` performs modulo, `{{ 10 % 3 }}` renders `1` 100 | 101 | They follow the usual priority rules (multiplication, division and modulo higher) but you can use parenthesis, `{{ (1 + 3) * 3 + 1 }}` renders: `13` 102 | 103 | > __A note about whitespace.__ Teruel is very whitespace sensitive, if your template isn't rendering check that you have just 1 whitespace between things. Things like 1+1 won't be recognised: please use 1 + 1 104 | 105 | 106 | ### Filters 107 | 108 | Values can be piped through a filter. A filter takes an input, some parameters (some filters only) and return an output. That output can be filtered too, making chains of filters. Filters use `|` to separate between them but the first one cannot be a filter, it needs to be a variable. 109 | 110 | For example: 111 | ``` 112 | {{ name | lower | truncate(length=4) }} 113 | ``` 114 | 115 | renders (Vars = ["name"-"Adrián"]) 116 | 117 | ``` 118 | adri 119 | ``` 120 | 121 | The complete list of filters Teruel has can be found below. 122 | 123 | 124 | ### Comparison and logic in expressions 125 | 126 | Expressions, as we said earlier, can also be used in some statements like if. If you want to use them there, you probably want to know about the comparisons and logic operators. If used directly, they will render `true` or `false`. 127 | 128 | To do comparisons: `==`, `!=`, `>=`, `<=`, `>` and `<` with their usual meanings. 129 | 130 | To combine comparisons, use the logic operators: `and`, `or` and `not` with their usual meanings. 131 | 132 | For example: 133 | ``` 134 | {{ 5 >= 4 or 3 < 1 }} 135 | ``` 136 | 137 | renders: 138 | 139 | ``` 140 | true 141 | ``` 142 | 143 | ## Statements 144 | 145 | Statements, `{%` and `%}`, can be used for more advanced stuff, like control flow and inheritance. 146 | 147 | ### If 148 | 149 | The `if` statement allows you to conditionally render a piece of template based on a expression. You can use `{% else %}` to render a piece of template if the expression is false. 150 | 151 | Let's see an example: 152 | 153 | ``` 154 | {% if user == "admin" %} 155 |

Welcome admin

156 | {% else %} 157 |

Welcome regular user

158 | {% endif %} 159 | ``` 160 | 161 | renders (Vars = ["user"-"admin"]): 162 | 163 | ``` 164 |

Welcome admin

165 | ``` 166 | 167 | ### For 168 | 169 | The `for` statement loops over a list, repeating the piece of template for each element on the list, which is available in a new created variable. 170 | 171 | ``` 172 | {% for link in links %} 173 | {{ link }} 174 | {% endfor %} 175 | ``` 176 | 177 | renders (Vars = ["links"-["https://github.com", "https://adrianistan.eu"]]) 178 | 179 | ``` 180 | https://github.com 181 | https://adrianistan.eu 182 | ``` 183 | 184 | ### Raw 185 | 186 | Teruel uses some special characters as delimiters, so you can't use them in your text code unless you put them inside a `raw` statement. This statements don't do any kind of processing inside, copying the content as-is. 187 | 188 | ``` 189 | {% raw %} 190 | {{ user }} 191 | {% endraw %} 192 | ``` 193 | 194 | renders: 195 | 196 | ``` 197 | {{ user }} 198 | ``` 199 | 200 | ### Filter 201 | 202 | You can also use filter statements to apply a filter to a large chunk of template. They cannot be chained, but they can be nested (you can put a filter statement inside of another one). 203 | 204 | ``` 205 | {% filter lower %} 206 | HELLO WORLD 207 | {% endfilter %} 208 | ``` 209 | 210 | renders: 211 | 212 | ``` 213 | hello world 214 | ``` 215 | 216 | ### Include 217 | 218 | Load the contents of another template file and put it there in the main file. You cannot use variables as the filename. 219 | 220 | ``` 221 | {% include "footer.html" %} 222 | ``` 223 | 224 | 225 | ### Block and extends (inheritance) 226 | 227 | Teruel supports Jinja-like inheritance. What does that mean? It means you can create documents based on a parent template and just filling the "blocks". 228 | 229 | For example, take a "base.html" template: 230 | ``` 231 | 232 | 233 | 234 | {% block head %} 235 | 236 | {% block title %}{% endblock %} - My Webpage 237 | {% endblock %} 238 | 239 | 240 |
{% block content %}{% endblock %}
241 | 246 | 247 | 248 | ``` 249 | 250 | It defines a template, with some pieces surrounded by block statements. This blocks can be overriden by other templates that extend this one. For example, a "child.html" could be: 251 | 252 | ``` 253 | {% extends "base.html" %} 254 | {% block title %}Index{% endblock %} 255 | {% block head %} 256 | {{ super }} 257 | {% raw %} 258 | 261 | {% endraw %} 262 | {% endblock %} 263 | {% block content %} 264 |

Index

265 |

266 | Welcome to my awesome homepage. 267 |

268 | {% endblock %} 269 | ``` 270 | Child templates must start with an `extends` statement and can only contain, at the top level, block statements. The block statements use the same identifier to override the default content of the original template. However, the special variable `super`, allows us to render the base.html block too. 271 | 272 | Rendering will give us: 273 | 274 | ``` 275 | 276 | 277 | 278 | 279 | Index - My Webpage 280 | 283 | 284 | 285 |
286 |

Index

287 |

288 | Welcome to my awesome homepage. 289 |

290 |
291 | 294 | 295 | 296 | ``` 297 | 298 | ## Filter list 299 | 300 | Here are the list of filters Teruel supports: 301 | 302 | * `lower` - Convert uppercase letters to lowercase 303 | * `upper` - Convert lowercase letters to uppercase 304 | * `length` - Counts the number of chars a string has or the number of items in a list 305 | * `wordcount` - Counts the number of words a string has 306 | * `capitalize` - Converts the first letter to uppercase, the rest to lowercase 307 | * `trim` - Removes the whitespaces at the start and at the end 308 | * `trim_start` - Removes the whitespaces at the start 309 | * `trim_end` - Remove the whitespaces at the end 310 | * `truncate(length=N)` - Truncates the string to the first N characters 311 | * `first` - First element of an array 312 | * `last` - Last element of an array 313 | * `nth(n=N)` - Element N of the array. Starts counting at 0 314 | * `replace(from=From, to=To)` - Replaces the From substring with the To substring in a bigger string. 315 | * `title` - Removes spaces and capitalizes the first letter of each word 316 | * `join(sep=Sep)` - Joins a list of strings with sep string in between 317 | * `reverse` - Reverse string or list 318 | * `sort` - Sort a list 319 | * `sort(key=Key)` - Sort a list by looking at the value of the key. Works for list of pairs. 320 | * `unique` - Removes duplicated elements 321 | * `floor` - Converts the number to the largest integer smaller or equal 322 | * `ceiling` - Converts the number to the smallest integer larger or equal 323 | -------------------------------------------------------------------------------- /examples/dice/Dice.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aarroyoc/teruel/3c1e0d206a45dc98bde8519360c7ab1bc9381ef3/examples/dice/Dice.gif -------------------------------------------------------------------------------- /examples/dice/README.md: -------------------------------------------------------------------------------- 1 | # Dice Sample 2 | 3 | This example demonstrates how to integrate the Scryer HTTP server with Teruel and htmx. 4 | 5 | ![Dice demo](Dice.gif) 6 | 7 | Running it: 8 | 9 | ``` 10 | scryer-prolog app.pl 11 | 12 | ?- listen(8080). 13 | ``` 14 | 15 | Visit http://localhost:8080 -------------------------------------------------------------------------------- /examples/dice/app.pl: -------------------------------------------------------------------------------- 1 | :- use_module(library(random)). 2 | :- use_module(lyncex). 3 | :- use_module(library(time)). 4 | :- use_module('../../teruel.pl'). 5 | 6 | listen(Port) :- 7 | http_listen(Port, [ 8 | get(/, index), 9 | get('dice.svg', dice), 10 | get('htmx.min.js', htmx) 11 | ]). 12 | 13 | index(_Request, Response) :- 14 | html_render_response(Response, "index.html"). 15 | 16 | dice(_Request, Response) :- 17 | random_integer(1, 7, N), 18 | time(render("dice.svg", ["n"-N], DiceSvg)),!, 19 | http_status_code(Response, 200), 20 | http_headers(Response, ["content-type"-"image/svg+xml"]), 21 | http_body(Response, text_custom(DiceSvg)). 22 | 23 | htmx(_Request, Response) :- 24 | http_status_code(Response, 200), 25 | http_headers(Response, ["content-type"-"text/javascript"]), 26 | http_body(Response, file("htmx.min.js")). -------------------------------------------------------------------------------- /examples/dice/dice.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {% if n == 1 %} 6 | 7 | {% endif %} 8 | {% if n == 2 %} 9 | 10 | 11 | {% endif %} 12 | {% if n == 3 %} 13 | 14 | 15 | 16 | {% endif %} 17 | {% if n == 4 %} 18 | 19 | 20 | 21 | 22 | {% endif %} 23 | {% if n == 5 %} 24 | 25 | 26 | 27 | 28 | 29 | {% endif %} 30 | {% if n == 6 %} 31 | 32 | 33 | 34 | 35 | 36 | 37 | {% endif %} 38 | -------------------------------------------------------------------------------- /examples/dice/htmx.min.js: -------------------------------------------------------------------------------- 1 | (function(e,t){if(typeof define==="function"&&define.amd){define([],t)}else{e.htmx=t()}})(typeof self!=="undefined"?self:this,function(){return function(){"use strict";var D={onLoad:t,process:rt,on:N,off:I,trigger:lt,ajax:$t,find:w,findAll:S,closest:O,values:function(e,t){var r=Ot(e,t||"post");return r.values},remove:E,addClass:C,removeClass:R,toggleClass:q,takeClass:L,defineExtension:Qt,removeExtension:er,logAll:b,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",disableSelector:"[hx-disable], [data-hx-disable]",useTemplateFragments:false,scrollBehavior:"smooth"},parseInterval:h,_:e,createEventSource:function(e){return new EventSource(e,{withCredentials:true})},createWebSocket:function(e){return new WebSocket(e,[])},version:"1.6.0"};var r=["get","post","put","delete","patch"];var n=r.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function h(e){if(e==undefined){return undefined}if(e.slice(-2)=="ms"){return parseFloat(e.slice(0,-2))||undefined}if(e.slice(-1)=="s"){return parseFloat(e.slice(0,-1))*1e3||undefined}return parseFloat(e)||undefined}function c(e,t){return e.getAttribute&&e.getAttribute(t)}function s(e,t){return e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function F(e,t){return c(e,t)||c(e,"data-"+t)}function l(e){return e.parentElement}function P(){return document}function d(e,t){if(t(e)){return e}else if(l(e)){return d(l(e),t)}else{return null}}function X(e,t){var r=null;d(e,function(e){return r=F(e,t)});if(r!=="unset"){return r}}function v(e,t){var r=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector;return r&&r.call(e,t)}function i(e){var t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;var r=t.exec(e);if(r){return r[1].toLowerCase()}else{return""}}function o(e,t){var r=new DOMParser;var n=r.parseFromString(e,"text/html");var i=n.body;while(t>0){t--;i=i.firstChild}if(i==null){i=P().createDocumentFragment()}return i}function u(e){if(D.config.useTemplateFragments){var t=o("",0);return t.querySelector("template").content}else{var r=i(e);switch(r){case"thead":case"tbody":case"tfoot":case"colgroup":case"caption":return o(""+e+"
",1);case"col":return o(""+e+"
",2);case"tr":return o(""+e+"
",2);case"td":case"th":return o(""+e+"
",3);case"script":return o("
"+e+"
",1);default:return o(e,0)}}}function U(e){if(e){e()}}function a(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function f(e){return a(e,"Function")}function g(e){return a(e,"Object")}function j(e){var t="htmx-internal-data";var r=e[t];if(!r){r=e[t]={}}return r}function p(e){var t=[];if(e){for(var r=0;r=0}function z(e){return P().body.contains(e)}function y(e){return e.trim().split(/\s+/)}function V(e,t){for(var r in t){if(t.hasOwnProperty(r)){e[r]=t[r]}}return e}function x(e){try{return JSON.parse(e)}catch(e){ut(e);return null}}function e(e){return Ut(P().body,function(){return eval(e)})}function t(t){var e=D.on("htmx:load",function(e){t(e.detail.elt)});return e}function b(){D.logger=function(e,t,r){if(console){console.log(t,e,r)}}}function w(e,t){if(t){return e.querySelector(t)}else{return w(P(),e)}}function S(e,t){if(t){return e.querySelectorAll(t)}else{return S(P(),e)}}function E(e,t){e=H(e);if(t){setTimeout(function(){E(e)},t)}else{e.parentElement.removeChild(e)}}function C(e,t,r){e=H(e);if(r){setTimeout(function(){C(e,t)},r)}else{e.classList&&e.classList.add(t)}}function R(e,t,r){e=H(e);if(r){setTimeout(function(){R(e,t)},r)}else{if(e.classList){e.classList.remove(t);if(e.classList.length===0){e.removeAttribute("class")}}}}function q(e,t){e=H(e);e.classList.toggle(t)}function L(e,t){e=H(e);B(e.parentElement.children,function(e){R(e,t)});C(e,t)}function O(e,t){e=H(e);if(e.closest){return e.closest(t)}else{do{if(e==null||v(e,t)){return e}}while(e=e&&l(e))}}function T(e,t){if(t.indexOf("closest ")===0){return[O(e,t.substr(8))]}else if(t.indexOf("find ")===0){return[w(e,t.substr(5))]}else if(t==="document"){return[document]}else if(t==="window"){return[window]}else{return P().querySelectorAll(t)}}function A(e,t){if(t){return T(e,t)[0]}else{return T(P().body,e)[0]}}function H(e){if(a(e,"String")){return w(e)}else{return e}}function k(e,t,r){if(f(t)){return{target:P().body,event:e,listener:t}}else{return{target:H(e),event:t,listener:r}}}function N(t,r,n){rr(function(){var e=k(t,r,n);e.target.addEventListener(e.event,e.listener)});var e=f(r);return e?r:n}function I(t,r,n){rr(function(){var e=k(t,r,n);e.target.removeEventListener(e.event,e.listener)});return f(r)?r:n}function _(e){var t=d(e,function(e){return F(e,"hx-target")!==null});if(t){var r=F(t,"hx-target");if(r==="this"){return t}else{return A(e,r)}}else{var n=j(e);if(n.boosted){return P().body}else{return e}}}function M(e){var t=D.config.attributesToSettle;for(var r=0;r0){i=e.substr(0,e.indexOf(":"));n=e.substr(e.indexOf(":")+1,e.length)}else{i=e}var o=P().querySelector(n);if(o){var a;a=P().createDocumentFragment();a.appendChild(t);if(!$(i,o)){a=t}le(i,o,o,a,r)}else{t.parentNode.removeChild(t);ot(P().body,"htmx:oobErrorNoTarget",{content:t})}return e}function Z(e,r){B(S(e,"[hx-swap-oob], [data-hx-swap-oob]"),function(e){var t=F(e,"hx-swap-oob");if(t!=null){J(t,e,r)}})}function G(e){B(S(e,"[hx-preserve], [data-hx-preserve]"),function(e){var t=F(e,"id");var r=P().getElementById(t);if(r!=null){e.parentNode.replaceChild(r,e)}})}function K(n,e,i){B(e.querySelectorAll("[id]"),function(e){if(e.id&&e.id.length>0){var t=n.querySelector(e.tagName+"[id='"+e.id+"']");if(t&&t!==n){var r=e.cloneNode();W(e,t);i.tasks.push(function(){W(e,r)})}}})}function Y(e){return function(){R(e,D.config.addedClass);rt(e);Ke(e);Q(e);lt(e,"htmx:load")}}function Q(e){var t="[autofocus]";var r=v(e,t)?e:e.querySelector(t);if(r!=null){r.focus()}}function ee(e,t,r,n){K(e,r,n);while(r.childNodes.length>0){var i=r.firstChild;C(i,D.config.addedClass);e.insertBefore(i,t);if(i.nodeType!==Node.TEXT_NODE&&i.nodeType!==Node.COMMENT_NODE){n.tasks.push(Y(i))}}}function te(t){var e=j(t);if(e.webSocket){e.webSocket.close()}if(e.sseEventSource){e.sseEventSource.close()}if(e.listenerInfos){B(e.listenerInfos,function(e){if(t!==e.on){e.on.removeEventListener(e.trigger,e.listener)}})}if(t.children){B(t.children,function(e){te(e)})}}function re(e,t,r){if(e.tagName==="BODY"){return se(e,t,r)}else{var n=e.previousSibling;ee(l(e),e,t,r);if(n==null){var i=l(e).firstChild}else{var i=n.nextSibling}j(e).replacedWith=i;r.elts=[];while(i&&i!==e){if(i.nodeType===Node.ELEMENT_NODE){r.elts.push(i)}i=i.nextElementSibling}te(e);l(e).removeChild(e)}}function ne(e,t,r){return ee(e,e.firstChild,t,r)}function ie(e,t,r){return ee(l(e),e,t,r)}function oe(e,t,r){return ee(e,null,t,r)}function ae(e,t,r){return ee(l(e),e.nextSibling,t,r)}function se(e,t,r){var n=e.firstChild;ee(e,n,t,r);if(n){while(n.nextSibling){te(n.nextSibling);e.removeChild(n.nextSibling)}te(n);e.removeChild(n)}}function ue(e,t){var r=X(e,"hx-select");if(r){var n=P().createDocumentFragment();B(t.querySelectorAll(r),function(e){n.appendChild(e)});t=n}return t}function le(e,t,r,n,i){switch(e){case"none":return;case"outerHTML":re(r,n,i);return;case"afterbegin":ne(r,n,i);return;case"beforebegin":ie(r,n,i);return;case"beforeend":oe(r,n,i);return;case"afterend":ae(r,n,i);return;default:var o=tr(t);for(var a=0;a-1){var t=e.replace(/]*>|>)([\s\S]*?)<\/svg>/gim,"");var r=t.match(/]*>|>)([\s\S]*?)<\/title>/im);if(r){return r[2]}}}function ce(e,t,r,n,i){var o=fe(n);if(o){var a=w("title");if(a){a.innerHTML=o}else{window.document.title=o}}var s=u(n);if(s){Z(s,i);s=ue(r,s);G(s);return le(e,r,t,s,i)}}function he(e,t,r){var n=e.getResponseHeader(t);if(n.indexOf("{")===0){var i=x(n);for(var o in i){if(i.hasOwnProperty(o)){var a=i[o];if(!g(a)){a={value:a}}lt(r,o,a)}}}else{lt(r,n,[])}}var de=/\s/;var ve=/[\s,]/;var ge=/[_$a-zA-Z]/;var pe=/[_$a-zA-Z0-9]/;var me=['"',"'","/"];var ye=/[^\s]/;function xe(e){var t=[];var r=0;while(r0){var a=t[0];if(a==="]"){n--;if(n===0){if(o===null){i=i+"true"}t.shift();i+=")})";try{var s=Ut(e,function(){return Function(i)()},function(){return true});s.source=i;return s}catch(e){ot(P().body,"htmx:syntax:error",{error:e,source:i});return null}}}else if(a==="["){n++}if(be(a,o,r)){i+="(("+r+"."+a+") ? ("+r+"."+a+") : (window."+a+"))"}else{i=i+a}o=t.shift()}}}function Se(e,t){var r="";while(e.length>0&&!e[0].match(t)){r+=e.shift()}return r}var Ee="input, textarea, select";function Ce(e){var t=F(e,"hx-trigger");var r=[];if(t){var n=xe(t);do{Se(n,ye);var i=n.length;var o=Se(n,/[,\[\s]/);if(o!==""){if(o==="every"){var a={trigger:"every"};Se(n,ye);a.pollInterval=h(Se(n,/[,\[\s]/));Se(n,ye);var s=we(e,n,"event");if(s){a.eventFilter=s}r.push(a)}else if(o.indexOf("sse:")===0){r.push({trigger:"sse",sseEvent:o.substr(4)})}else{var u={trigger:o};var s=we(e,n,"event");if(s){u.eventFilter=s}while(n.length>0&&n[0]!==","){Se(n,ye);var l=n.shift();if(l==="changed"){u.changed=true}else if(l==="once"){u.once=true}else if(l==="consume"){u.consume=true}else if(l==="delay"&&n[0]===":"){n.shift();u.delay=h(Se(n,ve))}else if(l==="from"&&n[0]===":"){n.shift();u.from=Se(n,ve)}else if(l==="target"&&n[0]===":"){n.shift();u.target=Se(n,ve)}else if(l==="throttle"&&n[0]===":"){n.shift();u.throttle=h(Se(n,ve))}else if(l==="queue"&&n[0]===":"){n.shift();u.queue=Se(n,ve)}else if((l==="root"||l==="threshold")&&n[0]===":"){n.shift();u[l]=Se(n,ve)}else{ot(e,"htmx:syntax:error",{token:n.shift()})}}r.push(u)}}if(n.length===i){ot(e,"htmx:syntax:error",{token:n.shift()})}Se(n,ye)}while(n[0]===","&&n.shift())}if(r.length>0){return r}else if(v(e,"form")){return[{trigger:"submit"}]}else if(v(e,Ee)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function Re(e){j(e).cancelled=true}function qe(e,t,r,n){var i=j(e);i.timeout=setTimeout(function(){if(z(e)&&i.cancelled!==true){if(!He(n,it("hx:poll:trigger",{triggerSpec:n}))){Zt(t,r,e)}qe(e,t,F(e,"hx-"+t),n)}},n.pollInterval)}function Le(e){return location.hostname===e.hostname&&c(e,"href")&&c(e,"href").indexOf("#")!==0}function Oe(t,r,e){if(t.tagName==="A"&&Le(t)||t.tagName==="FORM"){r.boosted=true;var n,i;if(t.tagName==="A"){n="get";i=c(t,"href");r.pushURL=true}else{var o=c(t,"method");n=o?o.toLowerCase():"get";if(n==="get"){r.pushURL=true}i=c(t,"action")}e.forEach(function(e){ke(t,n,i,r,e,true)})}}function Te(e){return e.tagName==="FORM"||v(e,'input[type="submit"], button')&&O(e,"form")!==null||e.tagName==="A"&&e.href&&(e.getAttribute("href")==="#"||e.getAttribute("href").indexOf("#")!==0)}function Ae(e,t){return j(e).boosted&&e.tagName==="A"&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function He(e,t){var r=e.eventFilter;if(r){try{return r(t)!==true}catch(e){ot(P().body,"htmx:eventFilter:error",{error:e,source:r.source});return true}}return false}function ke(o,a,s,e,u,l){var t;if(u.from){t=T(o,u.from)}else{t=[o]}B(t,function(n){var i=function(e){if(!z(o)){n.removeEventListener(u.trigger,i);return}if(Ae(o,e)){return}if(l||Te(o)){e.preventDefault()}if(He(u,e)){return}var t=j(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}var r=j(o);if(t.handledFor.indexOf(o)<0){t.handledFor.push(o);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!v(e.target,u.target)){return}}if(u.once){if(r.triggeredOnce){return}else{r.triggeredOnce=true}}if(u.changed){if(r.lastValue===o.value){return}else{r.lastValue=o.value}}if(r.delayed){clearTimeout(r.delayed)}if(r.throttle){return}if(u.throttle){if(!r.throttle){Zt(a,s,o,e);r.throttle=setTimeout(function(){r.throttle=null},u.throttle)}}else if(u.delay){r.delayed=setTimeout(function(){Zt(a,s,o,e)},u.delay)}else{Zt(a,s,o,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:i,on:n});n.addEventListener(u.trigger,i)})}var Ne=false;var Ie=null;function Me(){if(!Ie){Ie=function(){Ne=true};window.addEventListener("scroll",Ie);setInterval(function(){if(Ne){Ne=false;B(P().querySelectorAll("[hx-trigger='revealed'],[data-hx-trigger='revealed']"),function(e){De(e)})}},200)}}function De(e){var t=j(e);if(!t.revealed&&m(e)){t.revealed=true;if(t.initialized){Zt(t.verb,t.path,e)}else{e.addEventListener("htmx:afterProcessNode",function(){Zt(t.verb,t.path,e)},{once:true})}}}function Fe(e,t,r){var n=y(r);for(var i=0;i=0){var t=je(n);setTimeout(function(){Pe(s,r,n+1)},t)}};t.onopen=function(e){n=0};j(s).webSocket=t;t.addEventListener("message",function(e){if(Xe(s)){return}var t=e.data;st(s,function(e){t=e.transformResponse(t,null,s)});var r=Ft(s);var n=u(t);var i=p(n.children);for(var o=0;o0){lt(l,"htmx:validation:halted",i);return}t.send(JSON.stringify(u));if(Te(l)){e.preventDefault()}})}else{ot(l,"htmx:noWebSocketSourceError")}}function je(e){var t=D.config.wsReconnectDelay;if(typeof t==="function"){return t(e)}if(t==="full-jitter"){var r=Math.min(e,6);var n=1e3*Math.pow(2,r);return n*Math.random()}ut('htmx.config.wsReconnectDelay must either be a function or the string "full-jitter"')}function Be(e,t,r){var n=y(r);for(var i=0;iD.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){ot(P().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function dt(e){var t=x(localStorage.getItem("htmx-history-cache"))||[];for(var r=0;r=200&&this.status<400){lt(P().body,"htmx:historyCacheMissLoad",i);var e=u(this.response);e=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;var t=ct();var r=Ft(t);se(t,e,r);mt(r.tasks);ft=n;lt(P().body,"htmx:historyRestore",{path:n})}else{ot(P().body,"htmx:historyCacheMissLoadError",i)}};e.send()}function xt(e){gt();e=e||location.pathname+location.search;var t=dt(e);if(t){var r=u(t.content);var n=ct();var i=Ft(n);se(n,r,i);mt(i.tasks);document.title=t.title;window.scrollTo(0,t.scroll);ft=e;lt(P().body,"htmx:historyRestore",{path:e})}else{if(D.config.refreshOnHistoryMiss){window.location.reload(true)}else{yt(e)}}}function bt(e){var t=X(e,"hx-push-url");return t&&t!=="false"||j(e).boosted&&j(e).pushURL}function wt(e){var t=X(e,"hx-push-url");return t==="true"||t==="false"?null:t}function St(e){var t=X(e,"hx-indicator");if(t){var r=T(e,t)}else{r=[e]}B(r,function(e){e.classList["add"].call(e.classList,D.config.requestClass)});return r}function Et(e){B(e,function(e){e.classList["remove"].call(e.classList,D.config.requestClass)})}function Ct(e,t){for(var r=0;r=0}function Mt(e){var t=X(e,"hx-swap");var r={swapStyle:j(e).boosted?"innerHTML":D.config.defaultSwapStyle,swapDelay:D.config.defaultSwapDelay,settleDelay:D.config.defaultSettleDelay};if(j(e).boosted&&!It(e)){r["show"]="top"}if(t){var n=y(t);if(n.length>0){r["swapStyle"]=n[0];for(var i=1;i0?s.join(":"):null;r["scroll"]=u;r["scrollTarget"]=l}if(o.indexOf("show:")===0){var f=o.substr(5);var s=f.split(":");var c=s.pop();var l=s.length>0?s.join(":"):null;r["show"]=c;r["showTarget"]=l}}}}return r}function Dt(t,r,n){var i=null;st(r,function(e){if(i==null){i=e.encodeParameters(t,n,r)}});if(i!=null){return i}else{if(X(r,"hx-encoding")==="multipart/form-data"||v(r,"form")&&c(r,"enctype")==="multipart/form-data"){return Ht(n)}else{return At(n)}}}function Ft(e){return{tasks:[],elts:[e]}}function Pt(e,t){var r=e[0];var n=e[e.length-1];if(t.scroll){var i=null;if(t.scrollTarget){i=A(r,t.scrollTarget)}if(t.scroll==="top"&&(r||i)){i=i||r;i.scrollTop=0}if(t.scroll==="bottom"&&(n||i)){i=i||n;i.scrollTop=i.scrollHeight}}if(t.show){var i=null;if(t.showTarget){var o=t.showTarget;if(t.showTarget==="window"){o="body"}i=A(r,o)}if(t.show==="top"&&(r||i)){i=i||r;i.scrollIntoView({block:"start",behavior:D.config.scrollBehavior})}if(t.show==="bottom"&&(n||i)){i=i||n;i.scrollIntoView({block:"end",behavior:D.config.scrollBehavior})}}}function Xt(e,t,r,n){if(n==null){n={}}if(e==null){return n}var i=F(e,t);if(i){var o=i.trim();var a=r;if(o.indexOf("javascript:")===0){o=o.substr(11);a=true}else if(o.indexOf("js:")===0){o=o.substr(3);a=true}if(o.indexOf("{")!==0){o="{"+o+"}"}var s;if(a){s=Ut(e,function(){return Function("return ("+o+")")()},{})}else{s=x(o)}for(var u in s){if(s.hasOwnProperty(u)){if(n[u]==null){n[u]=s[u]}}}}return Xt(l(e),t,r,n)}function Ut(e,t,r){if(D.config.allowEval){return t()}else{ot(e,"htmx:evalDisallowedError");return r}}function jt(e,t){return Xt(e,"hx-vars",true,t)}function Bt(e,t){return Xt(e,"hx-vals",false,t)}function zt(e){return V(jt(e),Bt(e))}function Vt(t,r,n){if(n!==null){try{t.setRequestHeader(r,n)}catch(e){t.setRequestHeader(r,encodeURIComponent(n));t.setRequestHeader(r+"-URI-AutoEncoded","true")}}}function _t(t){if(t.responseURL&&typeof URL!=="undefined"){try{var e=new URL(t.responseURL);return e.pathname+e.search}catch(e){ot(P().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function Wt(e,t){return e.getAllResponseHeaders().match(t)}function $t(e,t,r){e=e.toLowerCase();if(r){if(r instanceof Element||a(r,"String")){return Zt(e,t,null,null,{targetOverride:H(r),returnPromise:true})}else{return Zt(e,t,H(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:H(r.target),returnPromise:true})}}else{return Zt(e,t,null,null,{returnPromise:true})}}function Jt(e){var t=[];while(e){t.push(e);e=e.parentElement}return t}function Zt(e,t,n,r,i){var o=null;var a=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var s=new Promise(function(e,t){o=e;a=t})}if(n==null){n=P().body}var u=i.handler||Gt;if(!z(n)){return}var l=i.targetOverride||_(n);if(l==null){ot(n,"htmx:targetError",{target:F(n,"hx-target")});return}var f=j(n);if(f.requestInFlight){var c="last";if(r){var h=j(r);if(h&&h.triggerSpec&&h.triggerSpec.queue){c=h.triggerSpec.queue}}if(f.queuedRequests==null){f.queuedRequests=[]}if(c==="first"&&f.queuedRequests.length===0){f.queuedRequests.push(function(){Zt(e,t,n,r,i)})}else if(c==="all"){f.queuedRequests.push(function(){Zt(e,t,n,r,i)})}else if(c==="last"){f.queuedRequests=[];f.queuedRequests.push(function(){Zt(e,t,n,r,i)})}return}else{f.requestInFlight=true}var d=function(){f.requestInFlight=false;if(f.queuedRequests!=null&&f.queuedRequests.length>0){var e=f.queuedRequests.shift();e()}};var v=X(n,"hx-prompt");if(v){var g=prompt(v);if(g===null||!lt(n,"htmx:prompt",{prompt:g,target:l})){U(o);d();return s}}var p=X(n,"hx-confirm");if(p){if(!confirm(p)){U(o);d();return s}}var m=new XMLHttpRequest;var y=kt(n,l,g);if(i.headers){y=V(y,i.headers)}var x=Ot(n,e);var b=x.errors;var w=x.values;if(i.values){w=V(w,i.values)}var S=zt(n);var E=V(w,S);var C=Nt(E,n);if(e!=="get"&&X(n,"hx-encoding")==null){y["Content-Type"]="application/x-www-form-urlencoded; charset=UTF-8"}if(t==null||t===""){t=P().location.href}var R=Xt(n,"hx-request");var q={parameters:C,unfilteredParameters:E,headers:y,target:l,verb:e,errors:b,withCredentials:i.credentials||R.credentials||D.config.withCredentials,timeout:i.timeout||R.timeout||D.config.timeout,path:t,triggeringEvent:r};if(!lt(n,"htmx:configRequest",q)){U(o);d();return s}t=q.path;e=q.verb;y=q.headers;C=q.parameters;b=q.errors;if(b&&b.length>0){lt(n,"htmx:validation:halted",q);U(o);d();return s}var L=t.split("#");var O=L[0];var T=L[1];if(e==="get"){var A=O;var H=Object.keys(C).length!==0;if(H){if(A.indexOf("?")<0){A+="?"}else{A+="&"}A+=At(C);if(T){A+="#"+T}}m.open("GET",A,true)}else{m.open(e.toUpperCase(),t,true)}m.overrideMimeType("text/html");m.withCredentials=q.withCredentials;m.timeout=q.timeout;if(R.noHeaders){}else{for(var k in y){if(y.hasOwnProperty(k)){var N=y[k];Vt(m,k,N)}}}var I={xhr:m,target:l,requestConfig:q,pathInfo:{path:t,finalPath:A,anchor:T}};m.onload=function(){try{var e=Jt(n);u(n,I);Et(M);lt(n,"htmx:afterRequest",I);lt(n,"htmx:afterOnLoad",I);if(!z(n)){var t=null;while(e.length>0&&t==null){var r=e.shift();if(z(r)){t=r}}if(t){lt(t,"htmx:afterRequest",I);lt(t,"htmx:afterOnLoad",I)}}U(o);d()}catch(e){ot(n,"htmx:onLoadError",V({error:e},I));throw e}};m.onerror=function(){Et(M);ot(n,"htmx:afterRequest",I);ot(n,"htmx:sendError",I);U(a);d()};m.onabort=function(){Et(M);ot(n,"htmx:afterRequest",I);ot(n,"htmx:sendAbort",I);U(a);d()};m.ontimeout=function(){Et(M);ot(n,"htmx:afterRequest",I);ot(n,"htmx:timeout",I);U(a);d()};if(!lt(n,"htmx:beforeRequest",I)){U(o);d();return s}var M=St(n);B(["loadstart","loadend","progress","abort"],function(t){B([m,m.upload],function(e){e.addEventListener(t,function(e){lt(n,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});lt(n,"htmx:beforeSend",I);m.send(e==="get"?null:Dt(m,n,C));return s}function Gt(a,s){var u=s.xhr;var l=s.target;if(!lt(a,"htmx:beforeOnLoad",s))return;if(Wt(u,/HX-Trigger:/i)){he(u,"HX-Trigger",a)}if(Wt(u,/HX-Push:/i)){var f=u.getResponseHeader("HX-Push")}if(Wt(u,/HX-Redirect:/i)){window.location.href=u.getResponseHeader("HX-Redirect");return}if(Wt(u,/HX-Refresh:/i)){if("true"===u.getResponseHeader("HX-Refresh")){location.reload();return}}var c=bt(a)||f;var e=u.status>=200&&u.status<400&&u.status!==204;var h=u.response;var t=V({shouldSwap:e,serverResponse:h},s);if(!lt(l,"htmx:beforeSwap",t))return;l=t.target;h=t.serverResponse;if(t.shouldSwap){if(u.status===286){Re(a)}st(a,function(e){h=e.transformResponse(h,u,a)});if(c){gt()}var d=Mt(a);l.classList.add(D.config.swappingClass);var r=function(){try{var e=document.activeElement;var t={};try{t={elt:e,start:e?e.selectionStart:null,end:e?e.selectionEnd:null}}catch(e){}var r=Ft(l);ce(d.swapStyle,l,a,h,r);if(t.elt&&!z(t.elt)&&t.elt.id){var n=document.getElementById(t.elt.id);if(n){if(t.start&&n.setSelectionRange){n.setSelectionRange(t.start,t.end)}n.focus()}}l.classList.remove(D.config.swappingClass);B(r.elts,function(e){if(e.classList){e.classList.add(D.config.settlingClass)}lt(e,"htmx:afterSwap",s)});if(s.pathInfo.anchor){location.hash=s.pathInfo.anchor}if(Wt(u,/HX-Trigger-After-Swap:/i)){var i=a;if(!z(a)){i=P().body}he(u,"HX-Trigger-After-Swap",i)}var o=function(){B(r.tasks,function(e){e.call()});B(r.elts,function(e){if(e.classList){e.classList.remove(D.config.settlingClass)}lt(e,"htmx:afterSettle",s)});if(c){var e=f||wt(a)||_t(u)||s.pathInfo.finalPath||s.pathInfo.path;pt(e);lt(P().body,"htmx:pushedIntoHistory",{path:e})}Pt(r.elts,d);if(Wt(u,/HX-Trigger-After-Settle:/i)){var t=a;if(!z(a)){t=P().body}he(u,"HX-Trigger-After-Settle",t)}};if(d.settleDelay>0){setTimeout(o,d.settleDelay)}else{o()}}catch(e){ot(a,"htmx:swapError",s);throw e}};if(d.swapDelay>0){setTimeout(r,d.swapDelay)}else{r()}}else{ot(a,"htmx:responseError",V({error:"Response Status Error Code "+u.status+" from "+s.pathInfo.path},s))}}var Kt={};function Yt(){return{onEvent:function(e,t){return true},transformResponse:function(e,t,r){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,r,n){return false},encodeParameters:function(e,t,r){return null}}}function Qt(e,t){Kt[e]=V(Yt(),t)}function er(e){delete Kt[e]}function tr(e,r,n){if(e==undefined){return r}if(r==undefined){r=[]}if(n==undefined){n=[]}var t=F(e,"hx-ext");if(t){B(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){n.push(e.slice(7));return}if(n.indexOf(e)<0){var t=Kt[e];if(t&&r.indexOf(t)<0){r.push(t)}}})}return tr(l(e),r,n)}function rr(e){if(P().readyState!=="loading"){e()}else{P().addEventListener("DOMContentLoaded",e)}}function nr(){if(D.config.includeIndicatorStyles!==false){P().head.insertAdjacentHTML("beforeend","")}}function ir(){var e=P().querySelector('meta[name="htmx-config"]');if(e){return x(e.content)}else{return null}}function or(){var e=ir();if(e){D.config=V(D.config,e)}}rr(function(){or();nr();var e=P().body;rt(e);window.onpopstate=function(e){if(e.state&&e.state.htmx){xt()}};setTimeout(function(){lt(e,"htmx:load",{})},0)});return D}()}); -------------------------------------------------------------------------------- /examples/dice/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Dice Webapp 5 | 6 | 7 | 8 | 20 | 21 | 22 |

Dice Webapp

23 |
24 | 25 |
26 | 27 | 28 | -------------------------------------------------------------------------------- /examples/dice/lyncex.pl: -------------------------------------------------------------------------------- 1 | /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 2 | Written in December 2020 by Adrián Arroyo (adrian.arroyocalle@gmail.com) 3 | Part of Scryer Prolog 4 | This library provides an starting point to build HTTP server based applications. 5 | It currently implements a subset of HTTP/1.0. It is recommended to put a reverse 6 | proxy like nginx in front of this server to have access to more advanced features 7 | (gzip compression, HTTPS, ...) 8 | Usage 9 | ========== 10 | The main predicate of the library is http_listen/2, which needs a port number 11 | (usually 80) and a list of handlers. A handler is a compound term with the functor 12 | as one HTTP method (in lowercase) and followed by a Route Match and a predicate 13 | which will handle the call. 14 | text_handler(Request, Response) :- 15 | http_status_code(Response, 200), 16 | http_body(Response, text("Welcome to Scryer Prolog!")). 17 | parameter_handler(User, Request, Response) :- 18 | http_body(Response, text(User)). 19 | http_listen(7890, [ 20 | get(echo, text_handler), % GET /echo 21 | post(user/User, parameter_handler(User)) % POST /user/ 22 | ]). 23 | Every handler predicate will have at least 2-arity, with Request and Response. 24 | Although you can work directly with http_request and http_response terms, it is 25 | recommeded to use the helper predicates, which are easier to understand and cleaner: 26 | - http_headers(Response/Request, Headers) 27 | - http_status_code(Responde, StatusCode) 28 | - http_body(Response/Request, text(Body)) 29 | - http_body(Response/Request, binary(Body)) 30 | - http_body(Request, form(Form)) 31 | - http_body(Response, file(Filename)) 32 | - http_redirect(Response, Url) 33 | - http_query(Request, QueryName, QueryValue) 34 | Some things that are still missing: 35 | - Read forms in multipart format 36 | - HTTP Basic Auth 37 | - Keep-Alive support 38 | - Session handling via cookies 39 | - HTML Templating 40 | I place this code in the public domain. Use it in any way you want. 41 | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ 42 | 43 | :- module(lyncex, [ 44 | http_listen/2, 45 | http_headers/2, 46 | http_status_code/2, 47 | http_body/2, 48 | http_redirect/2, 49 | http_query/3, 50 | url_decode//1 51 | ]). 52 | 53 | :- meta_predicate http_listen(?, 2). 54 | 55 | :- use_module(library(sockets)). 56 | :- use_module(library(dcgs)). 57 | :- use_module(library(format)). 58 | :- use_module(library(error)). 59 | :- use_module(library(charsio)). 60 | :- use_module(library(lists)). 61 | :- use_module(library(iso_ext)). 62 | :- use_module(library(time)). 63 | :- use_module(library(crypto)). 64 | 65 | % Module prefix workaround with meta_predicate 66 | http_listen(Port, Module:Handlers0) :- 67 | maplist(module_qualification(Module), Handlers0, Handlers), 68 | http_listen_(Port, Handlers). 69 | 70 | module_qualification(M, H0, H) :- 71 | H0 =.. [Method, Path, Goal], 72 | H =.. [Method, Path, M:Goal]. 73 | 74 | % Server initialization 75 | http_listen_(Port, Handlers) :- 76 | must_be(integer, Port), 77 | must_be(list, Handlers), 78 | once(socket_server_open('0.0.0.0':Port, Socket)), 79 | format("Listening at port ~d\n", [Port]), 80 | accept_loop(Socket, Handlers). 81 | 82 | % Server loop 83 | accept_loop(Socket, Handlers) :- 84 | setup_call_cleanup(socket_server_accept(Socket, _Client, Stream, [type(binary)]), 85 | ( 86 | read_header_lines(Stream, Lines), 87 | [Request|Headers] = Lines, 88 | ( 89 | (phrase(parse_request(_Version, Method, Path, Queries), Request), maplist(map_parse_header, Headers, HeadersKV)) -> ( 90 | ( 91 | member("content-length"-ContentLength, HeadersKV) -> 92 | (number_chars(ContentLengthN, ContentLength), get_bytes(Stream, ContentLengthN, Body)) 93 | ;true 94 | ), 95 | current_time(Time), 96 | phrase(format_time("%Y-%m-%d (%H:%M:%S)", Time), TimeString), 97 | format("~s ~w ~s\n", [TimeString, Method, Path]), 98 | ( 99 | match_handler(Handlers, Method, Path, Handler) -> 100 | ( 101 | HttpRequest = http_request(HeadersKV, binary(Body), Queries), 102 | HttpResponse = http_response(_, _, _), 103 | (call(Handler, HttpRequest, HttpResponse) -> 104 | send_response(Stream, HttpResponse) 105 | ; format(Stream, "HTTP/1.0 500 Internal Server Error\r\n\r\n", []) 106 | ) 107 | ) 108 | ; format(Stream, "HTTP/1.0 404 Not Found\r\n\r\n", []) 109 | ) 110 | );( 111 | format(Stream, "HTTP/1.0 400 Bad Request\r\n\r\n", []) % bad format 112 | ) 113 | ), 114 | ! % Remove 115 | ), close(Stream)), 116 | accept_loop(Socket, Handlers). 117 | 118 | match_handler(Handlers, Method, "/", Handler) :- 119 | member(H, Handlers), 120 | H =.. [Method, /, Handler]. 121 | match_handler(Handlers, Method, Path, Handler) :- 122 | member(H, Handlers), 123 | copy_term(H, H1), 124 | H1 =.. [Method, Pattern, Handler], 125 | \+ var(Pattern), 126 | phrase(path(Pattern), Path). 127 | match_handler(Handlers, Method, Path, Handler) :- 128 | member(H, Handlers), 129 | copy_term(H, H1), 130 | H1 =.. [Method, Var, Handler], 131 | var(Var), 132 | Var = Path. 133 | 134 | 135 | % Helper and recommended predicates 136 | 137 | http_headers(http_request(Headers, _, _), Headers). 138 | http_headers(http_response(_, _, Headers), Headers). 139 | 140 | http_body(http_request(_, binary(ByteBody), _), text(TextBody)) :- chars_utf8bytes(TextBody, ByteBody). 141 | http_body(http_request(Headers, binary(ByteBody), _), form(FormBody)) :- 142 | member("content-type"-"application/x-www-form-urlencoded", Headers), 143 | chars_utf8bytes(TextBody, ByteBody), 144 | phrase(parse_queries(FormBody), TextBody). 145 | http_body(http_request(_, Body, _), Body). 146 | http_body(http_response(_, Body, _), Body). 147 | 148 | http_status_code(http_response(StatusCode, _, _), StatusCode). 149 | 150 | http_redirect(http_response(307, text("Moved Temporarily"), ["Location"-Uri]), Uri). 151 | 152 | http_query(http_request(_, _, Queries), Key, Value) :- member(Key-Value, Queries). 153 | 154 | % Route matching 155 | path(Pattern) --> 156 | { 157 | Pattern =.. Parts, 158 | length(Parts, 3), 159 | nth0(1, Parts, Pattern0), 160 | nth0(2, Parts, PartAtom), 161 | (var(PartAtom) -> Part = PartAtom; atom_chars(PartAtom, Part)) 162 | }, 163 | path(Pattern0), 164 | "/", 165 | string_without("/", Part). 166 | 167 | path(Pattern) --> 168 | { 169 | Pattern =.. Parts, 170 | Parts = [PartAtom], 171 | (var(PartAtom) -> Part = PartAtom; atom_chars(PartAtom, Part)) 172 | }, 173 | "/", 174 | string_without("/", Part). 175 | 176 | path([]) --> []. 177 | 178 | % Send responses 179 | send_response(Stream, http_response(StatusCode0, file(Filename), Headers)) :- 180 | default(StatusCode0, 200, StatusCode), 181 | format(Stream, "HTTP/1.0 ~d\r\n", [StatusCode]), 182 | overwrite_header("connection"-"Close", Headers, Headers0), 183 | write_headers(Stream, Headers0), 184 | format(Stream, "\r\n", []), 185 | setup_call_cleanup( 186 | open(Filename, read, FileStream, [type(binary)]), 187 | pipe_bytes(FileStream, Stream), 188 | close(FileStream) 189 | ). 190 | 191 | send_response(Stream, http_response(StatusCode0, text(TextResponse), Headers)) :- 192 | default(StatusCode0, 200, StatusCode), 193 | format(Stream, "HTTP/1.0 ~d\r\n", [StatusCode]), 194 | overwrite_header("content-type"-"text/plain", Headers, Headers0), 195 | overwrite_header("connection"-"Close", Headers0, Headers1), 196 | write_headers(Stream, Headers1), 197 | format(Stream, "\r\n~s", [TextResponse]). 198 | 199 | send_response(Stream, http_response(StatusCode0, html(HtmlResponse), Headers)) :- 200 | default(StatusCode0, 200, StatusCode), 201 | format(Stream, "HTTP/1.0 ~d\r\n", [StatusCode]), 202 | overwrite_header("content-type"-"text/html", Headers, Headers0), 203 | overwrite_header("connection"-"Close", Headers0, Headers1), 204 | write_headers(Stream, Headers1), 205 | format(Stream, "\r\n~s", [HtmlResponse]). 206 | 207 | send_response(Stream, http_response(StatusCode0, text_custom(TextResponse), Headers)) :- 208 | default(StatusCode0, 200, StatusCode), 209 | format(Stream, "HTTP/1.0 ~d\r\n", [StatusCode]), 210 | overwrite_header("connection"-"Close", Headers, Headers0), 211 | write_headers(Stream, Headers0), 212 | format(Stream, "\r\n~s", [TextResponse]). 213 | 214 | send_response(Stream, http_response(StatusCode0, binary(BinaryResponse), Headers)) :- 215 | default(StatusCode0, 200, StatusCode), 216 | format(Stream, "HTTP/1.0 ~d\r\n", [StatusCode]), 217 | overwrite_header("connection"-"Close", Headers, Headers0), 218 | write_headers(Stream, Headers0), 219 | format(Stream, "\r\n", []), 220 | put_bytes(Stream, BinaryResponse). 221 | 222 | default(Var, Default, Out) :- 223 | (var(Var) -> Out = Default 224 | ; Var = Out 225 | ). 226 | 227 | header([]) --> []. 228 | header([Key-Value|Headers]) --> 229 | format_("~s: ~s\r\n", [Key, Value]), 230 | header(Headers). 231 | 232 | write_headers(Stream, Headers) :- 233 | phrase(header(Headers), Cs), 234 | format(Stream, "~s", [Cs]). 235 | 236 | overwrite_header(Key-Value, [], [Key-Value]). 237 | overwrite_header(Key-Value, [Header|Headers], [Header|HeadersOut]) :- 238 | Header = Key0-_, 239 | Key0 \= Key, 240 | overwrite_header(Key-Value, Headers, HeadersOut). 241 | overwrite_header(Key-Value, [Header|Headers], [NewHeader|Headers]) :- 242 | Header = Key-_, 243 | NewHeader = Key-Value. 244 | 245 | parse_request(http_version(Major, Minor), Method, Path, Queries) --> 246 | method(Method), 247 | " ", 248 | parse_path(Path, Queries), 249 | " ", 250 | "HTTP/", 251 | natural(Major), 252 | ".", 253 | natural(Minor), 254 | "\r\n". 255 | 256 | parse_path(Path, Queries) --> 257 | string_without("?", Path), 258 | "?", 259 | parse_queries(Queries). 260 | 261 | parse_path(Path, []) --> 262 | string_without(" ", Path). 263 | 264 | parse_queries([Key-Value|Queries]) --> 265 | string_without("=", Key0), 266 | { 267 | phrase(url_decode(Key), Key0) 268 | }, 269 | "=", 270 | string_without("&", Value0), 271 | { 272 | phrase(url_decode(Value), Value0) 273 | }, 274 | "&", 275 | parse_queries(Queries). 276 | 277 | parse_queries([Key-Value]) --> 278 | string_without("=", Key0), 279 | { 280 | phrase(url_decode(Key), Key0) 281 | }, 282 | "=", 283 | string_without(" ", Value0), 284 | { 285 | phrase(url_decode(Value), Value0) 286 | }. 287 | 288 | map_parse_header(Header, HeaderKV) :- 289 | phrase(parse_header(HeaderKV), Header). 290 | 291 | parse_header(Key-Value) --> 292 | string_without(":", Key0), 293 | { 294 | chars_lower(Key0, Key) 295 | }, 296 | ": ", 297 | string_without("\r", Value), 298 | "\r\n". 299 | 300 | method(options) --> "OPTIONS". 301 | method(get) --> "GET". 302 | method(head) --> "HEAD". 303 | method(post) --> "POST". 304 | method(put) --> "PUT". 305 | method(delete) --> "DELETE". 306 | 307 | string_without(Not, [Char|String]) --> 308 | [Char], 309 | { 310 | \+ member(Char, Not) 311 | }, 312 | string_without(Not, String). 313 | 314 | string_without(_, []) --> 315 | []. 316 | 317 | natural(Nat) --> 318 | natural_(NatChars), 319 | { 320 | number_chars(Nat, NatChars) 321 | }. 322 | 323 | natural_([Nat|Nats]) --> 324 | [Nat], 325 | { 326 | char_type(Nat, decimal_digit) 327 | }, 328 | natural_(Nats). 329 | 330 | natural_([]) --> 331 | []. 332 | 333 | read_header_lines(Stream, Hs) :- 334 | read_line_to_chars(Stream, Cs, []), 335 | ( Cs == "" -> Hs = [] 336 | ; Cs == "\r\n" -> Hs = [] 337 | ; Hs = [Cs|Rest], 338 | read_header_lines(Stream, Rest) 339 | ). 340 | 341 | get_bytes(Stream, Length, Res) :- get_bytes(Stream, Length, [], Res). 342 | get_bytes(Stream, Length, Acc, Res) :- 343 | (Length > 0 -> ( 344 | get_byte(Stream, B), 345 | B =\= -1, 346 | get_bytes(Stream, Length - 1, [B|Acc], Res) 347 | ); reverse(Acc, Res)). 348 | 349 | put_bytes(_, []). 350 | put_bytes(Stream, [Byte|Bytes]) :- 351 | put_byte(Stream, Byte), 352 | put_bytes(Stream, Bytes). 353 | 354 | pipe_bytes(StreamIn, StreamOut) :- 355 | get_byte(StreamIn, Byte), 356 | ( 357 | Byte =\= -1 -> 358 | ( 359 | put_byte(StreamOut, Byte), 360 | pipe_bytes(StreamIn, StreamOut) 361 | ) 362 | ; true). 363 | 364 | % WARNING: This only works for ASCII chars. This code can be modified to support 365 | % Latin1 characters also but a completely different approach is needed for other 366 | % languages. Since HTTP internals are ASCII, this is fine for this usecase. 367 | chars_lower(Chars, Lower) :- 368 | maplist(char_lower, Chars, Lower). 369 | char_lower(Char, Lower) :- 370 | char_code(Char, Code), 371 | ((Code >= 65,Code =< 90) -> 372 | LowerCode is Code + 32, 373 | char_code(Lower, LowerCode) 374 | ; Char = Lower). 375 | 376 | % Decodes a UTF-8 URL Encoded string: RFC-1738 377 | url_decode([Char|Chars]) --> 378 | [Char], 379 | { 380 | Char \= '%' 381 | }, 382 | url_decode(Chars). 383 | url_decode([Char|Chars]) --> 384 | "%", 385 | [A], 386 | [B], 387 | { 388 | hex_bytes([A,B], Bytes), 389 | Bytes = [FirstByte|_], 390 | FirstByte < 128, 391 | chars_utf8bytes(Chars0, Bytes), 392 | Chars0 = [Char] 393 | }, 394 | url_decode(Chars). 395 | url_decode([Char|Chars]) --> 396 | "%", 397 | [A, B], 398 | "%", 399 | [C, D], 400 | { 401 | hex_bytes([A,B,C,D], Bytes), 402 | Bytes = [FirstByte|_], 403 | FirstByte < 224, 404 | chars_utf8bytes(Chars0, Bytes), 405 | Chars0 = [Char] 406 | }, 407 | url_decode(Chars). 408 | url_decode([Char|Chars]) --> 409 | "%", 410 | [A, B], 411 | "%", 412 | [C, D], 413 | "%", 414 | [E, F], 415 | { 416 | hex_bytes([A,B,C,D,E,F], Bytes), 417 | Bytes = [FirstByte|_], 418 | FirstByte < 240, 419 | chars_utf8bytes(Chars0, Bytes), 420 | Chars0 = [Char] 421 | }, 422 | url_decode(Chars). 423 | url_decode([Char|Chars]) --> 424 | "%", 425 | [A, B], 426 | "%", 427 | [C, D], 428 | "%", 429 | [E, F], 430 | "%", 431 | [H, I], 432 | { 433 | hex_bytes([A,B,C,D,E,F,H,I], Bytes), 434 | chars_utf8bytes(Chars0, Bytes), 435 | Chars0 = [Char] 436 | }, 437 | url_decode(Chars). 438 | 439 | url_decode([]) --> []. -------------------------------------------------------------------------------- /expr.pl: -------------------------------------------------------------------------------- 1 | :- module(expr, [eval_expr/3, filter_//2]). 2 | 3 | :- use_module(library(dcgs)). 4 | :- use_module(library(charsio)). 5 | :- use_module(library(lists)). 6 | 7 | :- use_module(filters). 8 | 9 | % TODO: Concat 10 | % TODO: Lists 11 | % TODO: Builtins 12 | % TODO: Docs 13 | % TODO: In 14 | % TODO: CI 15 | % TODO: Birthday game 16 | % TODO: HTML Scaping 17 | 18 | eval_expr(ExprString, Vars, ExprValue) :- 19 | once(phrase(expr(ExprTree), ExprString)), 20 | eval(ExprTree, Vars, ExprOutValue), 21 | ( number(ExprOutValue) -> 22 | number_chars(ExprOutValue, ExprValue) 23 | ; ExprOutValue = true -> 24 | ExprValue = "true" 25 | ; ExprOutValue = false -> 26 | ExprValue = "false" 27 | ; ExprOutValue = ExprValue 28 | ). 29 | 30 | expr(filter(FilterName, X)) --> 31 | raw_string_(X), 32 | " | ", 33 | raw_string_(FilterName). 34 | 35 | expr(X) --> 36 | logic_expr(X). 37 | 38 | logic_expr(X) --> 39 | bool_expr(X). 40 | 41 | logic_expr(and(X, Y)) --> 42 | bool_expr(X), 43 | " and ", 44 | logic_expr(Y). 45 | 46 | logic_expr(or(X, Y)) --> 47 | bool_expr(X), 48 | " or ", 49 | logic_expr(Y). 50 | 51 | logic_expr(not(X)) --> 52 | "not ", 53 | logic_expr(X). 54 | 55 | bool_expr(X) --> 56 | sum_expr(X). 57 | 58 | bool_expr(eq(X, Y)) --> 59 | sum_expr(X), 60 | " == ", 61 | sum_expr(Y). 62 | 63 | bool_expr(ne(X, Y)) --> 64 | sum_expr(X), 65 | " != ", 66 | sum_expr(Y). 67 | 68 | bool_expr(lt(X, Y)) --> 69 | sum_expr(X), 70 | " < ", 71 | sum_expr(Y). 72 | 73 | bool_expr(gt(X, Y)) --> 74 | sum_expr(X), 75 | " > ", 76 | sum_expr(Y). 77 | 78 | bool_expr(le(X, Y)) --> 79 | sum_expr(X), 80 | " <= ", 81 | sum_expr(Y). 82 | 83 | bool_expr(ge(X, Y)) --> 84 | sum_expr(X), 85 | " >= ", 86 | sum_expr(Y). 87 | 88 | sum_expr(X) --> 89 | mul_expr(X). 90 | 91 | sum_expr(sum(X, Y)) --> 92 | mul_expr(X), 93 | " + ", 94 | sum_expr(Y). 95 | 96 | sum_expr(minus(X, Y)) --> 97 | mul_expr(X), 98 | " - ", 99 | sum_expr(Y). 100 | 101 | mul_expr(X) --> 102 | data_expr(X). 103 | 104 | mul_expr(mul(X, Y)) --> 105 | data_expr(X), 106 | " * ", 107 | mul_expr(Y). 108 | 109 | mul_expr(div(X, Y)) --> 110 | data_expr(X), 111 | " / ", 112 | mul_expr(Y). 113 | 114 | mul_expr(mod(X, Y)) --> 115 | data_expr(X), 116 | " % ", 117 | mul_expr(Y). 118 | 119 | 120 | data_expr(string(X)) --> 121 | "\"", 122 | raw_string_(X), 123 | "\"". 124 | 125 | data_expr(number(X)) --> 126 | number_(X). 127 | 128 | data_expr(bool(true)) --> 129 | "true". 130 | 131 | data_expr(bool(false)) --> 132 | "false". 133 | 134 | data_expr(par(X)) --> 135 | "(", 136 | raw_string_(X), 137 | ")". 138 | 139 | data_expr(var(X)) --> 140 | var_string_start_(X). 141 | 142 | eval(filter(FilterExpr, X), Vars, Value) :- 143 | once(phrase(expr(Tree), X)), 144 | eval(Tree, Vars, Value0), 145 | once(phrase(filter_(FilterName, FilterArgs), FilterExpr)), 146 | append("filter_", FilterName, FilterNameComplete), 147 | atom_chars(FilterAtom, FilterNameComplete), 148 | (FilterArgs = [] -> 149 | call(FilterAtom, Value0, Value) 150 | ; call(FilterAtom, Value0, Value, FilterArgs) 151 | ). 152 | 153 | 154 | eval(and(X, Y), Vars, Value) :- 155 | eval(X, Vars, XValue), 156 | ( XValue = true -> 157 | eval(Y, Vars, Value) 158 | ; Value = false 159 | ). 160 | 161 | eval(or(X, Y), Vars, Value) :- 162 | eval(X, Vars, XValue), 163 | ( XValue = false -> 164 | eval(Y, Vars, Value) 165 | ; Value = true 166 | ). 167 | 168 | eval(not(X), Vars, Value) :- 169 | eval(X, Vars, XValue), 170 | ( XValue = false -> 171 | Value = true 172 | ; Value = false 173 | ). 174 | 175 | eval(eq(X, Y), Vars, Value) :- 176 | eval(X, Vars, XValue), 177 | eval(Y, Vars, YValue), 178 | (XValue = YValue -> 179 | Value = true 180 | ; Value = false 181 | ). 182 | 183 | eval(ne(X, Y), Vars, Value) :- 184 | eval(X, Vars, XValue), 185 | eval(Y, Vars, YValue), 186 | (XValue = YValue -> 187 | Value = false 188 | ; Value = true 189 | ). 190 | 191 | eval(lt(X, Y), Vars, Value) :- 192 | eval(X, Vars, XValue), 193 | eval(Y, Vars, YValue), 194 | (XValue < YValue -> 195 | Value = true 196 | ; Value = false 197 | ). 198 | 199 | eval(le(X, Y), Vars, Value) :- 200 | eval(X, Vars, XValue), 201 | eval(Y, Vars, YValue), 202 | (XValue =< YValue -> 203 | Value = true 204 | ; Value = false 205 | ). 206 | 207 | eval(gt(X, Y), Vars, Value) :- 208 | eval(le(Y, X), Vars, Value). 209 | 210 | eval(ge(X, Y), Vars, Value) :- 211 | eval(lt(Y, X), Vars, Value). 212 | 213 | 214 | eval(mul(X, Y), Vars, Value) :- 215 | eval(X, Vars, XValue), 216 | eval(Y, Vars, YValue), 217 | Value is XValue * YValue. 218 | 219 | eval(div(X, Y), Vars, Value) :- 220 | eval(X, Vars, XValue), 221 | eval(Y, Vars, YValue), 222 | Value is XValue / YValue. 223 | 224 | eval(mod(X, Y), Vars, Value) :- 225 | eval(X, Vars, XValue), 226 | eval(Y, Vars, YValue), 227 | Value is XValue mod YValue. 228 | 229 | eval(sum(X, Y), Vars, Value) :- 230 | eval(X, Vars, XValue), 231 | eval(Y, Vars, YValue), 232 | Value is XValue + YValue. 233 | 234 | eval(minus(X, Y), Vars, Value) :- 235 | eval(X, Vars, XValue), 236 | eval(Y, Vars, YValue), 237 | Value is XValue - YValue. 238 | 239 | eval(number(X), _, N) :- 240 | number_chars(N, X). 241 | eval(string(X), _, X). 242 | eval(bool(X), _, X). 243 | eval(var(X), Vars, Value) :- 244 | phrase(var_dict_get(Value, Vars, []), X). 245 | eval(par(X), Vars, Value) :- 246 | once(phrase(expr(Tree), X)), 247 | eval(Tree, Vars, Value). 248 | 249 | filter_(FilterName, FilterArgs) --> 250 | raw_string_(FilterName), 251 | "(", 252 | !, 253 | filter_args_(FilterArgs), 254 | ")". 255 | 256 | filter_(FilterName, []) --> 257 | raw_string_(FilterName). 258 | 259 | filter_args_([ArgName-ArgValue|FilterArgs]) --> 260 | raw_string_(ArgName), 261 | "=", 262 | data_expr(ArgValue), 263 | ", ", 264 | filter_args_(FilterArgs). 265 | 266 | filter_args_([ArgName-ArgValue]) --> 267 | raw_string_(ArgName), 268 | "=", 269 | data_expr(ArgValue). 270 | 271 | var_dict_get(Value, Vars, Key) --> 272 | [X], 273 | { 274 | X \= '.', 275 | append(Key, [X], NewKey) 276 | }, 277 | var_dict_get(Value, Vars, NewKey). 278 | 279 | var_dict_get(Value, Vars, Key) --> 280 | ".", 281 | { 282 | member(Key-NewVars, Vars) 283 | }, 284 | var_dict_get(Value, NewVars, []). 285 | 286 | var_dict_get(Value, Vars, Key) --> 287 | [], 288 | { 289 | member(Key-Value, Vars) 290 | }. 291 | 292 | var_string_start_([C|X]) --> 293 | [C], 294 | { 295 | char_type(C, alphabetic) 296 | }, 297 | var_string_(X). 298 | 299 | var_string_([C|X]) --> 300 | [C], 301 | { 302 | char_type(C, alnum) 303 | }, 304 | var_string_(X). 305 | 306 | var_string_(['.'|X]) --> 307 | ".", 308 | var_string_(X). 309 | 310 | var_string_([]) --> 311 | []. 312 | 313 | raw_string_([X|Xs]) --> 314 | [X], 315 | raw_string_(Xs). 316 | 317 | raw_string_([]) --> 318 | []. 319 | 320 | number_([D|Ds]) --> digit(D), number_(Ds). 321 | number_([D]) --> digit(D). 322 | 323 | digit(D) --> [D], { char_type(D, decimal_digit) }. 324 | digit(D) --> [D], { D = '.'}. 325 | -------------------------------------------------------------------------------- /expr_tests.lgt: -------------------------------------------------------------------------------- 1 | :- use_module(expr). 2 | 3 | :- object(expr, extends(lgtunit)). 4 | 5 | test(var, true(Result == "aarroyoc")) :- 6 | expr:eval_expr("username", ["username"-"aarroyoc"], Result). 7 | 8 | test(dict_var, true(Result == "aarroyoc")) :- 9 | expr:eval_expr("user.login", ["user"-["login"-"aarroyoc", "password"-"123456"]], Result). 10 | 11 | test(number, true(Result == "42")) :- 12 | expr:eval_expr("42", [], Result). 13 | 14 | test(string, true(Result == "foo")) :- 15 | expr:eval_expr("\"foo\"", [], Result). 16 | 17 | test(bool, true(Result == "true")) :- 18 | expr:eval_expr("true", [], Result). 19 | 20 | test(sum_2, true(Result == "3")) :- 21 | expr:eval_expr("1 + 2", [], Result). 22 | 23 | test(sum_3, true(Result == "6")) :- 24 | expr:eval_expr("1 + 2 + 3", [], Result). 25 | 26 | test(sum_minus, true(Result == "0")) :- 27 | expr:eval_expr("1 + 2 - 3", [], Result). 28 | 29 | test(mul, true(Result == "11")) :- 30 | expr:eval_expr("1 + 3 * 3 + 1", [], Result). 31 | 32 | test(mul_par, true(Result == "13")) :- 33 | expr:eval_expr("(1 + 3) * 3 + 1", [], Result). 34 | 35 | test(sum_float, true(Result == "1.5")) :- 36 | expr:eval_expr("0.75 + 0.75", [], Result). 37 | 38 | test(div, true(Result == "0")) :- 39 | expr:eval_expr("1 - 2 / 2 | floor", [], Result). 40 | 41 | test(equal, true(Result == "true")) :- 42 | expr:eval_expr("1 + 2 == 3", [], Result). 43 | 44 | test(not_equal, true(Result == "false")) :- 45 | expr:eval_expr("3 + 1 != 2 * 2", [], Result). 46 | 47 | test(and, true(Result == "true")) :- 48 | expr:eval_expr("5 > 4 and 4 > 3", [], Result). 49 | 50 | test(or, true(Result == "true")) :- 51 | expr:eval_expr("5 >= 4 or 3 < 1", [], Result). 52 | 53 | test(not, true(Result == "false")) :- 54 | expr:eval_expr("not false or true", [], Result). 55 | 56 | test(filter, true(Result == "aarroyoc")) :- 57 | expr:eval_expr("username | lower", ["username"-"AARROYOC"], Result). 58 | 59 | test(multi_filter, true(Result == "8")) :- 60 | expr:eval_expr("user.login | lower | length", ["user"-["login"-"aarroyoc", "password"-"123456"]], Result). 61 | 62 | test(filter_param, true(Result == "aarr")) :- 63 | expr:eval_expr("user.login | lower | truncate(length=4)", ["user"-["login"-"aarroyoc", "password"-"123456"]], Result). 64 | 65 | test(nth, true(Result == "https://adrianistan.eu")) :- 66 | expr:eval_expr("links | nth(n=1)", ["links"-["https://github.com", "https://adrianistan.eu"]], Result). 67 | 68 | test(replace, true(Result == "aarropuc")) :- 69 | expr:eval_expr("username | replace(from=\"yo\", to=\"pu\")", ["username"-"aarroyoc"], Result). 70 | 71 | :- end_object. 72 | -------------------------------------------------------------------------------- /filters.pl: -------------------------------------------------------------------------------- 1 | :- module(filters, [ 2 | filter_lower/2, 3 | filter_upper/2, 4 | filter_length/2, 5 | filter_wordcount/2, 6 | filter_capitalize/2, 7 | filter_trim/2, 8 | filter_trim_start/2, 9 | filter_trim_end/2, 10 | filter_truncate/3, 11 | filter_first/2, 12 | filter_last/2, 13 | filter_nth/3, 14 | filter_replace/3, 15 | filter_title/2, 16 | filter_join/3, 17 | filter_reverse/2, 18 | filter_sort/2, 19 | filter_sort/3, 20 | filter_unique/2, 21 | filter_floor/2, 22 | filter_ceiling/2 23 | ]). 24 | 25 | :- use_module(library(dcgs)). 26 | :- use_module(library(lists)). 27 | :- use_module(library(pairs)). 28 | 29 | % TODO: https://github.com/mthom/scryer-prolog/issues/748 30 | filter_lower(In, Out) :- 31 | maplist(char_lower, In, Out). 32 | 33 | char_lower(Char, Lower) :- 34 | char_code(Char, Code), 35 | ((Code >= 65,Code =< 90) -> 36 | LowerCode is Code + 32, 37 | char_code(Lower, LowerCode) 38 | ; Char = Lower). 39 | 40 | filter_upper(In, Out) :- 41 | maplist(char_upper, In, Out). 42 | 43 | char_upper(Char, Upper) :- 44 | char_code(Char, Code), 45 | ((Code >= 97,Code =< 122) -> 46 | UpperCode is Code - 32, 47 | char_code(Upper, UpperCode) 48 | ; Char = Upper). 49 | 50 | filter_length(In, Out) :- 51 | length(In, N), 52 | number_chars(N, Out). 53 | 54 | filter_wordcount(In, Out) :- 55 | once(phrase(wordsplit_(Words), In)), 56 | length(Words, N), 57 | number_chars(N, Out). 58 | 59 | wordsplit_(Words) --> 60 | " ", 61 | wordsplit_(Words). 62 | wordsplit_([]) --> 63 | word_([]). 64 | wordsplit_([Word|Words]) --> 65 | word_(Word), 66 | wordsplit_(Words). 67 | 68 | word_([Char|Chars]) --> 69 | [Char], 70 | { 71 | \+ member(Char, " "), 72 | ! 73 | }, 74 | word_(Chars). 75 | word_([]) --> []. 76 | 77 | filter_capitalize([First|Rest], [UpperFirst|LowerRest]) :- 78 | char_upper(First, UpperFirst), 79 | filter_lower(Rest, LowerRest). 80 | 81 | filter_trim(In, Out) :- 82 | filter_trim_start(In, S), 83 | filter_trim_end(S, Out). 84 | 85 | filter_trim_start([' '|In], Out) :- 86 | filter_trim_start(In, Out). 87 | filter_trim_start([X|In], [X|In]) :- 88 | X \= ' '. 89 | 90 | filter_trim_end(In, Out) :- 91 | reverse(In, RIn), 92 | filter_trim_start(RIn, ROut), 93 | reverse(ROut, Out). 94 | 95 | filter_truncate(In, Out, Args) :- 96 | member("length"-number(NString), Args), 97 | number_chars(N, NString), 98 | append(Out, _, In), 99 | length(Out, N). 100 | 101 | filter_first([Out|_], Out). 102 | 103 | filter_last([X], X). 104 | filter_last([_|Xs], Out) :- 105 | filter_last(Xs, Out). 106 | 107 | filter_nth(In, Out, Args) :- 108 | member("n"-number(NString), Args), 109 | number_chars(N, NString), 110 | nth0(N, In, Out). 111 | 112 | filter_replace(In, Out, Args) :- 113 | member("from"-string(From), Args), 114 | member("to"-string(To), Args), 115 | once(phrase(replace_(From, To, Out), In)). 116 | 117 | 118 | replace_(From, To, Out) --> 119 | string_(X), 120 | string_(From), 121 | { 122 | \+ append(From, _, X), 123 | append(X, To, Section), 124 | append(Section, Xs, Out) 125 | }, 126 | replace_(From, To, Xs). 127 | 128 | replace_(From, _, X) --> 129 | string_(X), 130 | { 131 | \+ append(From, _, X) 132 | }. 133 | 134 | filter_title(In, Out) :- 135 | once(phrase(wordsplit_(Words), In)), 136 | maplist(filter_capitalize, Words, TitleWords), 137 | once(phrase(join_(" ", TitleWords), Out)). 138 | 139 | join_(Joiner, [X|Xs]) --> 140 | string_(X), 141 | string_(Joiner), 142 | join_(Joiner, Xs). 143 | join_(_, [X]) --> 144 | string_(X). 145 | 146 | filter_join(In, Out, Args) :- 147 | member("sep"-string(Joiner), Args), 148 | once(phrase(join_(Joiner, In), Out)). 149 | 150 | filter_reverse(In, Out) :- 151 | reverse(In, Out). 152 | 153 | filter_sort(In, Out) :- 154 | sort(In, Out). 155 | 156 | filter_sort(In, Out, Args) :- 157 | member("key"-string(Key), Args), 158 | map_list_to_pairs(get_key(Key), In, Pairs), 159 | keysort(Pairs, Sorted), 160 | pairs_values(Sorted, Out). 161 | 162 | get_key(Key, Item, Value) :- 163 | member(Key-Value, Item). 164 | 165 | 166 | filter_unique(In, Out) :- 167 | list_to_set(In, Out). 168 | 169 | filter_floor(In, Out) :- 170 | Out is floor(In). 171 | 172 | filter_ceiling(In, Out) :- 173 | Out is ceiling(In). 174 | 175 | string_([X|Xs]) --> 176 | [X], 177 | string_(Xs). 178 | 179 | string_([]) --> 180 | []. 181 | -------------------------------------------------------------------------------- /filters_tests.lgt: -------------------------------------------------------------------------------- 1 | :- use_module(filters). 2 | 3 | :- object(filters, extends(lgtunit)). 4 | 5 | test(lower, true(Result == "abc")) :- 6 | filters:filter_lower("AbC", Result). 7 | 8 | test(upper, true(Result == "ABC")) :- 9 | filters:filter_upper("aBc", Result). 10 | 11 | test(length, true(Result == "5")) :- 12 | filters:filter_length("abc ", Result). 13 | 14 | test(wordcount, true(Result == "4")) :- 15 | filters:filter_wordcount(" hola amigos de Perú", Result). 16 | 17 | test(capitalize, true(Result == "Abc")) :- 18 | filters:filter_capitalize("abc", Result). 19 | 20 | test(trim, true(Result == "hola amigos")) :- 21 | filters:filter_trim(" hola amigos ", Result). 22 | 23 | test(trim_start, true(Result == "hola amigos ")) :- 24 | filters:filter_trim_start(" hola amigos ", Result). 25 | 26 | test(trim_end, true(Result == " hola amigos")) :- 27 | filters:filter_trim_end(" hola amigos ", Result). 28 | 29 | test(truncate, true(Result == "hola")) :- 30 | filters:filter_truncate("hola amigos", Result, ["length"-number("4")]). 31 | 32 | test(first, true(Result == 1)) :- 33 | filters:filter_first([1,2,3], Result). 34 | 35 | test(last, true(Result == 3)) :- 36 | filters:filter_last([1,2,3], Result). 37 | 38 | test(nth, true(Result == 2)) :- 39 | filters:filter_nth([1,2,3], Result, ["n"-number("1")]). 40 | 41 | test(replace, true(Result == "adios amigos")) :- 42 | filters:filter_replace("hola amigos", Result, ["from"-string("hola"), "to"-string("adios")]). 43 | 44 | test(title, true(Result == "Hola Amigos Cruel")) :- 45 | filters:filter_title("hola amigos cruel", Result). 46 | 47 | test(join, true(Result == "hola//amigos//cruel")) :- 48 | filters:filter_join(["hola", "amigos", "cruel"], Result, ["sep"-string("//")]). 49 | 50 | test(reverse, true(Result == "sogima aloh")) :- 51 | filters:filter_reverse("hola amigos", Result). 52 | 53 | test(simple_sort, true(Result == [1,2,3,4])) :- 54 | filters:filter_sort([4,2,1,3], Result). 55 | 56 | test(complex_sort, true(Result == [["age"-21, "name"-"Marisa"], ["age"-34, "name"-"Pepe"], ["age"-56, "name"-"César"]])) :- 57 | filters:filter_sort([["age"-34, "name"-"Pepe"], ["age"-21, "name"-"Marisa"], ["age"-56, "name"-"César"]], Result, ["key"-string("age")]). 58 | 59 | test(unique, true(Result == [1,2,3])) :- 60 | filters:filter_unique([1,2,3,1,2,3], Result). 61 | 62 | :- end_object. -------------------------------------------------------------------------------- /parser.pl: -------------------------------------------------------------------------------- 1 | :- module(parser, [parser//2, canonical_dir/2]). 2 | 3 | :- use_module(library(lists)). 4 | :- use_module(library(pio)). 5 | :- use_module(library(files)). 6 | :- use_module(library(dcgs)). 7 | 8 | % Try to implement most of Tera: https://tera.netlify.app/docs/#templates 9 | 10 | parser([], _) --> []. 11 | parser([Node|Ast], Path) --> 12 | ( 13 | parser_expr(Node) 14 | ; parser_raw(Node) 15 | ; parser_filter(Node, Path) 16 | ; parser_if(Node, Path) 17 | ; parser_for(Node, Path) 18 | ; parser_include(Node, Path) 19 | ; parser_extends(Node, Path) 20 | ; parser_block(Node, Path) 21 | ; parser_comment 22 | ; parser_text(Node) 23 | ), 24 | parser(Ast, Path). 25 | 26 | parser_expr(expr(X)) --> 27 | "{{ ", 28 | seq(X), 29 | " }}". 30 | 31 | parser_raw(raw(X)) --> 32 | "{% raw %}", 33 | seq(X), 34 | "{% endraw %}". 35 | 36 | parser_filter(filter(Filter, X), Path) --> 37 | "{% filter ", 38 | seq(Filter), 39 | " %}", 40 | parser_in_filter(X, Path). 41 | 42 | parser_if(if(Expr, If, Else), Path) --> 43 | "{% if ", 44 | seq(Expr), 45 | " %}", 46 | parser_in_if(If, Else, Path). 47 | 48 | parser_for(for(LocalVar, ListExpr, X), Path) --> 49 | "{% for ", 50 | seq(LocalVar), 51 | " in ", 52 | seq(ListExpr), 53 | " %}",!, 54 | parser_in_for(X, Path). 55 | 56 | parser_include(include(X), Path) --> 57 | "{% include \"", 58 | seq(File), 59 | "\" %}", 60 | { 61 | concat_path(Path, File, PathFile), 62 | canonical_dir(PathFile, PathDir), 63 | once(phrase_from_file(parser(X, PathDir), PathFile)) 64 | }. 65 | 66 | parser_extends(extends(X, Blocks), Path) --> 67 | "{% extends \"", 68 | seq(File), 69 | "\" %}", 70 | parser_blocks(Blocks, Path), 71 | { 72 | concat_path(Path, File, PathFile), 73 | canonical_dir(PathFile, PathDir), 74 | phrase_from_file(parser(X, PathDir), PathFile) 75 | }. 76 | 77 | parser_block(block(Name, X), Path) --> 78 | "{% block ", 79 | seq(Name), 80 | " %}", 81 | seq(Content), 82 | "{% endblock %}", 83 | { phrase(parser(X, Path), Content) }. 84 | 85 | parser_comment --> 86 | "{#", 87 | seq(_), 88 | "#}". 89 | 90 | parser_text(text([C])) --> [C]. 91 | 92 | parser_in_for([], _) --> "{% endfor %}". 93 | parser_in_for([Node|Ast], Path) --> 94 | ( 95 | parser_expr(Node) 96 | ; parser_raw(Node) 97 | ; parser_filter(Node, Path) 98 | ; parser_if(Node, Path) 99 | ; parser_for(Node, Path) 100 | ; parser_include(Node, Path) 101 | ; parser_comment 102 | ; parser_text(Node) 103 | ), 104 | parser_in_for(Ast, Path). 105 | 106 | parser_in_if([],[], _) --> "{% endif %}". 107 | parser_in_if([], Else, Path) --> 108 | "{% else %}", 109 | parser_in_else(Else, Path). 110 | parser_in_if([Node|Ast], Else, Path) --> 111 | ( 112 | parser_expr(Node) 113 | ; parser_raw(Node) 114 | ; parser_filter(Node, Path) 115 | ; parser_if(Node, Path) 116 | ; parser_for(Node, Path) 117 | ; parser_include(Node, Path) 118 | ; parser_comment 119 | ; parser_text(Node) 120 | ), 121 | parser_in_if(Ast, Else, Path). 122 | 123 | parser_in_else([], _) --> "{% endif %}". 124 | parser_in_else([Node|Ast], Path) --> 125 | ( 126 | parser_expr(Node) 127 | ; parser_raw(Node) 128 | ; parser_filter(Node, Path) 129 | ; parser_if(Node, Path) 130 | ; parser_for(Node, Path) 131 | ; parser_include(Node, Path) 132 | ; parser_comment 133 | ; parser_text(Node) 134 | ), 135 | parser_in_else(Ast, Path). 136 | 137 | parser_in_filter([], _) --> "{% endfilter %}". 138 | parser_in_filter([Node|Ast], Path) --> 139 | ( 140 | parser_expr(Node) 141 | ; parser_raw(Node) 142 | ; parser_filter(Node, Path) 143 | ; parser_if(Node, Path) 144 | ; parser_for(Node, Path) 145 | ; parser_include(Node, Path) 146 | ; parser_comment 147 | ; parser_text(Node) 148 | ), 149 | parser_in_filter(Ast, Path). 150 | 151 | 152 | look_ahead(T), [T] --> [T]. 153 | 154 | % Parser for child templates 155 | 156 | parser_blocks([Name-X|Blocks], Path) --> 157 | seq(_), 158 | "{% block ", 159 | seq(Name), 160 | " %}", 161 | parser_in_block(X, Path), 162 | parser_blocks(Blocks, Path). 163 | parser_blocks([], _) --> whitespace_. 164 | 165 | parser_in_block([], _) --> "{% endblock %}". 166 | parser_in_block([Node|Ast], Path) --> 167 | ( 168 | parser_expr(Node) 169 | ; parser_raw(Node) 170 | ; parser_filter(Node, Path) 171 | ; parser_if(Node, Path) 172 | ; parser_for(Node, Path) 173 | ; parser_include(Node, Path) 174 | ; parser_extends(Node, Path) 175 | ; parser_block(Node, Path) 176 | ; parser_comment 177 | ; parser_text(Node) 178 | ), 179 | parser_in_block(Ast, Path). 180 | 181 | whitespace_ --> 182 | [X], 183 | { 184 | memberchk(X, " \t\n\r") 185 | }, 186 | whitespace_. 187 | 188 | whitespace_ --> []. 189 | 190 | canonical_dir(Chars, FolderPath) :- 191 | path_canonical(Chars, Path), 192 | path_segments(Path, PathSegments), 193 | once(append(FolderPathSegments, [_], PathSegments)), 194 | path_segments(FolderPath, FolderPathSegments). 195 | 196 | concat_path(Path, File, PathFile) :- 197 | path_segments(Path, P0), 198 | path_segments(File, P1), 199 | append(P0, P1, P2), 200 | path_segments(PathFile, P2). 201 | 202 | contains(X, In) :- 203 | append(_, Y, X), 204 | append(In, _, Y). 205 | -------------------------------------------------------------------------------- /parser_tests.lgt: -------------------------------------------------------------------------------- 1 | :- use_module(parser). 2 | 3 | :- object(parser, extends(lgtunit)). 4 | 5 | test(expr_basic) :- 6 | phrase(parser:parser(Ast, ""), "Hola"), 7 | Ast = [text("H"), text("o"), text("l"), text("a")]. 8 | 9 | test(expr_for_in_for) :- 10 | phrase(parser:parser(Ast, ""), "{% for post in posts %}{% for comment in post.comments %}{{ comment.id }}{% endfor %}{% for author in post.authors %}{{ author.name }}{% endfor %}{% endfor %}"), 11 | Ast = [for("post","posts",[for("comment","post.comments",[expr("comment.id")]),for("author","post.authors",[expr("author.name")])])]. 12 | 13 | :- end_object. 14 | -------------------------------------------------------------------------------- /render.pl: -------------------------------------------------------------------------------- 1 | :- module(render, [render_tree/3]). 2 | 3 | :- use_module(library(lists)). 4 | :- use_module(library(dcgs)). 5 | 6 | :- use_module(expr). 7 | :- use_module(filters). 8 | 9 | render_tree(Tree, Vars, Output) :- 10 | maplist(render_node(Vars), Tree, Outputs), 11 | append(Outputs, Output). 12 | 13 | render_node(_Vars, text(X), X). 14 | 15 | render_node(Vars, expr(ExprString), Output) :- 16 | eval_expr(ExprString, Vars, Output). 17 | 18 | render_node(_Vars, raw(X), X). 19 | 20 | render_node(Vars, filter(FilterExpr, X), Output) :- 21 | render_tree(X, Vars, Output0), 22 | once(phrase(filter_(FilterName, FilterArgs), FilterExpr)), 23 | append("filter_", FilterName, FilterNameComplete), 24 | atom_chars(FilterAtom, FilterNameComplete), 25 | (FilterArgs = [] -> 26 | call(FilterAtom, Output0, Output) 27 | ; call(FilterAtom, Output0, Output, FilterArgs) 28 | ). 29 | 30 | render_node(Vars, if(Expr, X, Y), Output) :- 31 | eval_expr(Expr, Vars, Result), 32 | ( Result = "true" -> 33 | render_tree(X, Vars, Output) 34 | ; render_tree(Y, Vars, Output) 35 | ). 36 | 37 | render_node(Vars, for(LocalVar, ListExpr, X), Output) :- 38 | eval_expr(ListExpr, Vars, ListValues), 39 | maplist(render_for(LocalVar, X, Vars), ListValues, SubOutputs), 40 | append(SubOutputs, Output). 41 | 42 | render_node(Vars, include(X), Output) :- 43 | render_tree(X, Vars, Output). 44 | 45 | render_node(Vars, extends(X, Blocks), Output) :- 46 | maplist(prefix_blocks, Blocks, VarBlocks), 47 | append(Vars, VarBlocks, VarsExtends), 48 | render_tree(X, VarsExtends, Output). 49 | 50 | render_node(Vars, block(Name, X), Output) :- 51 | append("__block__", Name, VarBlockName), 52 | findall(Block, member(VarBlockName-Block, Vars), BlocksR), 53 | reverse(BlocksR, Blocks), 54 | render_block([X|Blocks], Vars, Output). 55 | 56 | render_block([Block], Vars, Output) :- 57 | render_tree(Block, Vars, Output). 58 | render_block([Block|Blocks], Vars, Output) :- 59 | render_tree(Block, Vars, Super), 60 | render_block(Blocks, ["super"-Super|Vars], Output). 61 | 62 | 63 | render_for(LocalVar, LocalNode, Vars, ListValue, Output) :- 64 | append(Vars, [LocalVar-ListValue], LocalVars), 65 | render_tree(LocalNode, LocalVars, Output). 66 | 67 | prefix_blocks(BlockName-Block, VarBlockName-Block) :- 68 | append("__block__", BlockName, VarBlockName). 69 | -------------------------------------------------------------------------------- /templates/a.in.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Título 6 | 7 | 8 |

Welcome to Teruel

9 |

{{ username }}

10 | 11 | -------------------------------------------------------------------------------- /templates/a.out.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Título 6 | 7 | 8 |

Welcome to Teruel

9 |

aarroyoc

10 | 11 | -------------------------------------------------------------------------------- /templates/b.in.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Título 6 | 7 | 8 |

Welcome to Teruel

9 |

{{ username }}

10 |

{% raw %} Hello {{ name }} {% endraw %}

11 | 12 | -------------------------------------------------------------------------------- /templates/b.out.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Título 6 | 7 | 8 |

Welcome to Teruel

9 |

aarroyoc

10 |

Hello {{ name }}

11 | 12 | -------------------------------------------------------------------------------- /templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | {% block head %} 5 | 6 | {% block title %}{% endblock %} - My Webpage 7 | {% endblock %} 8 | 9 | 10 |
{% block content %}{% endblock %}
11 | 16 | 17 | -------------------------------------------------------------------------------- /templates/c.in.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Título 6 | 7 | 8 |

Welcome to Teruel

9 | {#

De momento desactivado {{ username }}

#} 10 | 11 | -------------------------------------------------------------------------------- /templates/c.out.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Título 6 | 7 | 8 |

Welcome to Teruel

9 | 10 | 11 | -------------------------------------------------------------------------------- /templates/child.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% block title %}Index{% endblock %} 3 | {% block head %} 4 | {{ super }} 5 | {% raw %} 6 | 9 | {% endraw %} 10 | {% endblock %} 11 | {% block content %} 12 |

Index

13 |

14 | Welcome to my awesome homepage. 15 |

16 | {% endblock %} 17 | -------------------------------------------------------------------------------- /templates/child.out.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Index - My Webpage 8 | 9 | 10 | 13 | 14 | 15 | 16 | 17 |
18 |

Index

19 |

20 | Welcome to my awesome homepage. 21 |

22 |
23 | 28 | 29 | -------------------------------------------------------------------------------- /templates/child3.html: -------------------------------------------------------------------------------- 1 | {% extends "parent.html" %} 2 | {% block hey %}dad says {{ super }}{% endblock %} -------------------------------------------------------------------------------- /templates/d.in.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Título 6 | 7 | 8 |

Welcome to Teruel

9 |

Expr 1 {{ 1 + 1 }}

10 |

Expr 2 {{ 2 - 1 }}

11 |

Expr 3 {{ 1 + 1 + 1 }}

12 |

Expr 4 {{ "Hola Mundo" }}

13 |

Expr 5 {{ true }}

14 |

Expr 6 {{ 6 * 7 }}

15 |

Expr 7 {{ 1 + 2 * 2 + 1 }}

16 |

Expr 8 {{ 2 + 2 == 4 }}

17 |

Expr 9 {{ 2 + 1 == 3 - 1 }}

18 |

Expr 10 {{ "admin" != username }}

19 |

Expr 11 {{ 1200 > 100 + 10 }}

20 |

Expr 12 {{ 1200 >= 100 + 10 }}

21 |

Expr 13 {{ true and false and true }}

22 |

Expr 14 {{ 4 > 2 or 3 == 2 }}

23 | 24 | -------------------------------------------------------------------------------- /templates/d.out.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Título 6 | 7 | 8 |

Welcome to Teruel

9 |

Expr 1 2

10 |

Expr 2 1

11 |

Expr 3 3

12 |

Expr 4 Hola Mundo

13 |

Expr 5 true

14 |

Expr 6 42

15 |

Expr 7 6

16 |

Expr 8 true

17 |

Expr 9 false

18 |

Expr 10 true

19 | 20 | -------------------------------------------------------------------------------- /templates/e.in.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Título 6 | 7 | 8 |

Welcome to Teruel

9 | {% filter lower %} 10 |

Expr 1 {{ 1 + 1 }}

11 |

Expr 2 {{ 2 - 1 }}

12 |

Expr 3 {{ 1 + 1 + 1 }}

13 | {% filter wordcount %} 14 |

Expr 4 {{ "Hola Mundo" }}

15 | {% endfilter %} 16 |

Expr 5 {{ true }}

17 |

Expr 6 {{ 6 * 7 }}

18 |

Expr 7 {{ 1 + 2 * 2 + 1 }}

19 |

Expr 8 {{ 2 + 2 == 4 }}

20 |

Expr 9 {{ 2 + 1 == 3 - 1 }}

21 |

Expr 10 {{ "admin" != username }}

22 |

Expr 11 {{ 1200 > 100 + 10 }}

23 |

Expr 12 {{ 1200 >= 100 + 10 }}

24 |

Expr 13 {{ true and false and true }}

25 |

Expr 14 {{ 4 > 2 or 3 == 2 }}

26 | {% endfilter %} 27 | 28 | -------------------------------------------------------------------------------- /templates/f.in.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Título 6 | 7 | 8 |

Welcome to Teruel

9 | {% if username == "admin" %} 10 |

Welcome admin!

11 | {% endif %} 12 | {% if username != "admin" %} 13 |

{{ username }}

14 | {% if 2 * 2 == 4 %} 15 |

Good good

16 | {% endif %} 17 | {% endif %} 18 | 19 | -------------------------------------------------------------------------------- /templates/footer.html: -------------------------------------------------------------------------------- 1 |
2 | © {{ username }} 2021 3 |
-------------------------------------------------------------------------------- /templates/g.in.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Título 6 | 7 | 8 |

Welcome to Teruel

9 | {% if username == "admin" %} 10 |

Welcome admin!

11 | {% else %} 12 |

{{ username }}

13 | {% if 2 * 2 == 4 %} 14 |

Good good

15 | {% endif %} 16 | {% endif %} 17 | 18 | -------------------------------------------------------------------------------- /templates/grandparent.html: -------------------------------------------------------------------------------- 1 | {% block hey %}hello{% endblock %} -------------------------------------------------------------------------------- /templates/h.in.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Título 6 | 7 | 8 |

Welcome to Teruel

9 | {% for link in links %} 10 |

{{ link }}

11 | {% endfor %} 12 | 13 | -------------------------------------------------------------------------------- /templates/h.out.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Título 6 | 7 | 8 |

Welcome to Teruel

9 |

https://github.com

10 |

https://adrianistan.eu

11 | 12 | -------------------------------------------------------------------------------- /templates/i.in.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Título 6 | 7 | 8 |

Welcome to Teruel

9 | {% for link in links %} 10 |

{{ link }}

11 | {% endfor %} 12 | {% include "footer.html" %} 13 | 14 | -------------------------------------------------------------------------------- /templates/issue-4.in.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Issue 4 5 | 6 | 7 | {% raw %} 8 | {{ hola }} 9 | {% endraw %} 10 | {% raw %} 11 | {{ hola }} 12 | {% endraw %} 13 | 14 | -------------------------------------------------------------------------------- /templates/j.in.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Título 6 | 7 | 8 |

Welcome to Teruel

9 | {% for web in webs | sort(key="popularity") %} 10 |

{{ web.name }}

11 | {% endfor %} 12 | 13 | -------------------------------------------------------------------------------- /templates/j.out.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Título 6 | 7 | 8 |

Welcome to Teruel

9 |

GitHub

10 |

Google

11 | 12 | -------------------------------------------------------------------------------- /templates/parent.html: -------------------------------------------------------------------------------- 1 | {% extends "grandparent.html" %} 2 | {% block hey %}hi and grandma says {{ super }} {% endblock %} -------------------------------------------------------------------------------- /teruel.pl: -------------------------------------------------------------------------------- 1 | :- module(teruel, [render/3, html_render_response/2, html_render_response/3]). 2 | 3 | :- use_module(library(dcgs)). 4 | :- use_module(library(pio)). 5 | :- use_module(library(lists)). 6 | :- use_module(library(files)). 7 | 8 | :- use_module(parser). 9 | :- use_module(render). 10 | 11 | render(Input, Vars, Output) :- 12 | canonical_dir(Input, FolderPath), 13 | once(phrase_from_file(parser(Tree, FolderPath), Input)), 14 | render_tree(Tree, Vars, Output). 15 | 16 | html_render_response(Response, Input) :- 17 | html_render_response(Response, Input, []). 18 | 19 | html_render_response(http_response(_, html(Output), _), Input, Vars) :- 20 | render(Input, Vars, Output). 21 | -------------------------------------------------------------------------------- /tester.lgt: -------------------------------------------------------------------------------- 1 | :- initialization(( 2 | set_logtalk_flag(report, warnings), 3 | set_logtalk_flag(unknown_entities, silent), 4 | logtalk_load(lgtunit(loader)), 5 | logtalk_load(parser_tests, [hook(lgtunit)]), 6 | logtalk_load(expr_tests, [hook(lgtunit)]), 7 | logtalk_load(filters_tests, [hook(lgtunit)]), 8 | lgtunit::run_test_sets([parser, expr, filters]) 9 | )). 10 | -------------------------------------------------------------------------------- /tests.lgt: -------------------------------------------------------------------------------- 1 | :- use_module(teruel). 2 | 3 | :- object(tests, extends(lgtunit)). 4 | 5 | test(trivial, true) :- 6 | true. 7 | 8 | test(simple_substitution, true(Assertion)) :- 9 | template_test("templates/a.in.html", "templates/a.out.html", ["username"-"aarroyoc"], Assertion). 10 | 11 | test(raw_block, true(Assertion)) :- 12 | template_test("templates/b.in.html", "templates/b.out.html", ["username"-"aarroyoc"], Assertion). 13 | 14 | test(comment_block, true(Assertion)) :- 15 | template_test("templates/c.in.html", "templates/c.out.html", ["username"-"aarroyoc"], Assertion). 16 | 17 | test(for_loop, true(Assertion)) :- 18 | template_test("templates/h.in.html", "templates/h.out.html", ["username"-"aarroyoc", "links"-["https://github.com", "https://adrianistan.eu"]], Assertion). 19 | 20 | test(for_loop_filter, true(Assertion)) :- 21 | template_test("templates/j.in.html", "templates/j.out.html", ["webs"-[["name"-"Google", "popularity"-100], ["name"-"GitHub", "popularity"-40]]], Assertion). 22 | 23 | % auxiliary predicates 24 | 25 | template_test(In, Out, Vars, Assertion) :- 26 | teruel:render(In, Vars, OutputReal), 27 | ^^text_file_assertion(Out, OutputReal, Assertion). 28 | 29 | :- end_object. --------------------------------------------------------------------------------