### Nimja Block Rendering for Dynamic Content (HTMX Example) Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Provides an example of using Nimja's `blockToRender` feature in conjunction with HTMX. It shows how to render the entire page initially and then selectively render a specific block (e.g., 'button') for partial updates. ```nimja
{% block content %}

Hello

{% block button %}
{%- if button == 10%}you klicked enough!!{% endif -%}
{% endblock %} {% endblock %} ``` ```nim tmplf("page.nimja", baseDir = getScriptDir()) ``` ```nim tmplf("page.nimja", blockToRender = "button" baseDir = getScriptDir()) ``` ```nimja {% block button %}
{%- if button == 10%}you klicked enough!!{% endif -%}
{% endblock %} ``` -------------------------------- ### Nimja Syntax Transformation Example Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Demonstrates the transformation of Nimja template syntax into equivalent Nim code. It shows how variable access, method calls, and comments are converted. ```text - `{{ myObj.myVar }}` --transformed-to---> `$(myObj.myVar)` - {% myExpression.inc() %} --transformed-to---> `myExpression.inc()` - {# a comment #} ``` -------------------------------- ### Nim Example for Rendering Child Template Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Demonstrates how to compile and render a Nimja child template using Nim code. This example uses `compileTemplateFile` and specifies the `baseDir`. ```nim proc renderChild(): string = compileTemplateFile("child.nimja", baseDir = getScriptDir()) echo renderChild() ``` -------------------------------- ### Nimja Macro Definition and Usage Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Demonstrates how to define a macro in Nimja using the `macro` keyword and how to invoke it with parameters. The example shows a basic textarea macro. ```nimja {% macro textarea(name, value="", rows=10, cols=40): string = %} {% endmacro %} {{ textarea("name", "value") }} ``` -------------------------------- ### Nimja Template Inheritance Example Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Illustrates Nimja template inheritance using Jinja2-like syntax. `index.nimja` and `detail.nimja` extend a master layout defined in `_master.nimja`. This demonstrates how to set up a base template and override specific blocks within derived templates for structure and content management. ```html {% extends "templates/partials/_master.nimja" %} {% block content %}

Hello, world! {{foos}}

index {% for idx in 0..100 %} {{idx}} {%- endfor %} {% endblock %} ``` ```html {% extends "templates/partials/_master.nimja" %} {% block content %} detail {{id}} {% endblock %} ``` ```html Hello, world!

Nimja dynamic test

{% block content %}{% endblock %}
``` -------------------------------- ### Nimja Benchmark Example Source: https://github.com/enthus1ast/nimja/blob/master/readme.md This snippet demonstrates a performance benchmark for the Nimja template engine, comparing its speed against other engines. It's based on a benchmark script from the dekao project. The primary dependency is the Nim compiler and potentially the 'dekao' project for the benchmark itself. ```nim # https://github.com/enthus1ast/dekao/blob/master/bench.nim ``` -------------------------------- ### Nimja Hot Code Reloading - Host File Source: https://github.com/enthus1ast/nimja/blob/master/readme.md An example of the host application file (`host.nim`) for Nimja's hot code reloading. It utilizes `nimja/hcrutils` to watch for template changes and recompile them dynamically. ```nim # this is the file that eg. implements your webserver and loads # the templates as a shared lib. import nimja/hcrutils # Nimja's hot code reloading utilities import jester, os # We watch the templates folder for change (and also tmpls.nim implicitly) var cw = newChangeWatcher(@[getAppDir() / "templates/"]) asyncCheck cw.recompile() # if a change is detected we recompile tmpls.nim type # You must declare the proc definition from your tmpls.nim here as well. ProcNoParam = proc (): string {.gcsafe, stdcall.} ProcId = proc (id: string): string {.gcsafe, stdcall.} routes: get "/": resp dyn(ProcNoParam, "index") get "/id/@id": resp dyn(ProcId, "detail", @"id") ``` -------------------------------- ### Nimja Hot Code Reloading - Templates File Source: https://github.com/enthus1ast/nimja/blob/master/readme.md An example of the template file (`tmpls.nim`) used with Nimja's hot code reloading. This file is intended to contain only render functions and is compiled into a shared library. ```nim # this file contains you render functions # is compiled to a shared lib and loaded by your host application # to keep compilation fast, use this file only for templates. # this file is also watched by the filewatcher. ``` -------------------------------- ### Compile Nim Template String with Base Directory Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Shows how to use `compileTemplateStr` to compile a Nimja template directly from a string. It includes the use of `baseDir` for potential template imports or extensions, though not strictly necessary for this basic example. ```nim proc myRenderProc(someParam: string): string = compileTemplateStr("some nimja code {{someParam}}", baseDir = getScriptDir()) echo myRenderProc("test123") ``` -------------------------------- ### Nim Loop Iterator Example Source: https://github.com/enthus1ast/nimja/blob/master/src/nimja/htmldocs/nimjautils.html Demonstrates the usage of the 'loop' iterator in Nim, which provides enhanced loop variables like index, length, and status flags. The example shows how to access these variables and use them within a loop, often in conjunction with HTML list items. ```nim {% for loop, row in rows.loop() %} {{ loop.index0 }} {{ loop.index }} {{ loop.revindex0 }} {{ loop.revindex }} {{ loop.length }} {% if loop.first %}The first item{% endif %} {% if loop.last %}The last item{% endif %} {% if loop.previtem.isSome %}{{ loop.previtem.get() }}{% endif %} {% if loop.nextitem.isSome %}{{ loop.nextitem.get() }}{% endif %}
  • {{row}}
  • {% endfor %} ``` -------------------------------- ### Nim Cycle Procedure Example Source: https://github.com/enthus1ast/nimja/blob/master/src/nimja/htmldocs/nimjautils.html Illustrates the 'cycle' procedure in Nim, which allows cycling through a list of elements based on the current loop iteration. This is commonly used for alternating styles, such as 'odd' and 'even' classes in HTML lists. ```nim {% for loop, row in rows.loop() %}
  • {{ row }}
  • {% endfor %} ``` -------------------------------- ### Nimja Template Conditional Logic (if/elif/else) Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Provides an example of using `if`, `elif`, and `else` statements within a Nimja template for conditional rendering. This mirrors standard conditional logic found in many templating languages. ```twig {% if aa == 1 %} aa is: one {% elif aa == 2 %} aa is: two {% else %} aa is something else {% endif %} ``` -------------------------------- ### Nimja Template Compilation to Nim Code Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Illustrates how Nimja compiles a template string containing conditional logic and variable manipulation into executable Nim code. The example shows a template with an if statement and variable increment being transformed. ```nim proc foo(ss: string, ii: int): string = compileTemplateStr( """example{% if ii == 1%}{{ss}}{% endif %}{% var myvar = 1 %}{% myvar.inc %} """) is transformed to: proc foo(ss: string; ii: int): string = result &= "example" if ii == 1: result &= ss var myvar = 1 inc(myvar, 1) ``` -------------------------------- ### Get Script Directory at Compile Time (Nim) Source: https://github.com/enthus1ast/nimja/blob/master/docs/nimja/sharedhelper.html The getScriptDir function returns the absolute path to the project at compile time. It's a helper primarily used by staticRead. ```nim template getScriptDir(): string ``` -------------------------------- ### Nimja Loop with Array Iteration Source: https://github.com/enthus1ast/nimja/blob/master/playground/browser/article1.html Demonstrates iterating over a hardcoded array using Nimja's `for` loop syntax. It accesses both the loop index and the current item in each iteration. The `repeat` method is used on the item, with the number of repetitions determined by the loop index. ```nimja {% for (loop, each) in @["foo", "baa", "baz"].loop() %} {{ each.repeat(loop.index) }} {% endfor %} ``` -------------------------------- ### Shorthand Conditional Class Template (Nim) Source: https://github.com/enthus1ast/nimja/blob/master/docs/nimja/nimjautils.html Provides a shorthand syntax `?` for conditionally applying a class based on a boolean variable. For example, `{% ?isDisabled: "disable" %}` will render the class 'disable' only if `isDisabled` is true. This simplifies common HTML class manipulations. ```nim template `?`(con, body: untyped): untyped ``` ```html ``` -------------------------------- ### String Concatenation with Tilde (Nim) Source: https://github.com/enthus1ast/nimja/blob/master/docs/nimja/nimjautils.html Defines the `~` (tilde) operator to convert its operands to strings and concatenate them. This provides a fluent way to build strings, similar to string interpolation or concatenation in other languages. Example: `"Hello " ~ name ~ "!"`. ```nim template ~ (aa, bb: untyped): string ``` -------------------------------- ### Combining Nimja Partial and Extended Templates Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Demonstrates how Nimja's block rendering can be used to combine extended templates with partials. It shows a `user.nimja` template that extends a base partial and defines its own content and user blocks. ```nimja {% extends partials/_base.nimja %} {% block content %} Information about the user. {% block user %}
    {{user.firstName}} {{user.lastName}}
    {% endblock %} also visit other user! {% endblock %} ``` -------------------------------- ### Import Nimja Template Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Imports a Nimja template file and renders it. ```nimja {% importnimja "user.nimja" "user" %} ``` -------------------------------- ### VSCode Nimja Template Association for Syntax Highlighting Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Provides instructions for configuring VSCode to associate `.nimja` and `.nwt` files with HTML syntax highlighting and formatting. This is achieved by adding a specific JSON snippet to the VSCode `settings.json` file, enabling better development experience for Nimja templates. ```json "files.associations": { "*.nwt": "html", // Nimja deprecated templates "*.nimja": "html", // Nimja new templates }, ``` -------------------------------- ### Nim Server Rendering with Nimja Templates Source: https://github.com/enthus1ast/nimja/blob/master/readme.md This Nim code snippet demonstrates how to set up an asynchronous HTTP server using `asynchttpserver` and `asyncdispatch`. It uses the `nimja` library to compile and render HTML templates, passing dynamic data like user information to the templates. The `renderIndex` procedure compiles a Nimja template file into Nim code, allowing for direct access to variables within the template. ```nim import asynchttpserver, asyncdispatch import nimja/parser import os, random # os and random are later used in the templates, so imported here type User = object name: string lastname: string age: int proc renderIndex(title: string, users: seq[User]): string = ## the `index.nimja` template is transformed to nim code. ## so it can access all variables like `title` and `users` ## the return variable could be `string` or `Rope` or ## anything which has a `&=`(obj: YourObj, str: string) proc. compileTemplateFile("index.nimja", baseDir = getScriptDir()) proc main {.async.} = var server = newAsyncHttpServer() proc cb(req: Request) {.async.} = # in the templates we can later loop trough this sequence let users: seq[User] = @[ User(name: "Katja", lastname: "Kopylevych", age: 32), User(name: "David", lastname: "Krause", age: 32), ] await req.respond(Http200, renderIndex("index", users)) server.listen Port(8080) while true: if server.shouldAcceptRequest(): await server.acceptRequest(cb) else: poll() asyncCheck main() runForever() ``` -------------------------------- ### Nim Compile Command Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Provides the basic command to compile and run a Nim application. It also shows the force compilation flag for cases where changes are not detected. ```bash nim c -r yourfile.nim ``` ```bash nim c -f -r yourfile.nim ``` -------------------------------- ### Nimja Helper Functions Source: https://github.com/enthus1ast/nimja/blob/master/docs/theindex.html Documentation for helper functions related to script directories and file reading. ```APIDOC ## SHAREDHELPER FUNCTIONS ### Description This section covers helper functions for accessing script directories and reading file content. ### `getScriptDir` (template) - **Description**: Retrieves the directory of the currently executing script. - **Module**: nimja/sharedhelper - **Signature**: `template getScriptDir(): string` ### `read` (template) - **Description**: Reads the content of a file at compile time. - **Module**: nimja/sharedhelper - **Signature**: `template read(path: untyped): untyped` - **Parameters**: - `path` (untyped) - The path to the file to read. ### Request Example ```nim # Example usage of getScriptDir let scriptDir = getScriptDir() echo "Current script directory: ", scriptDir # Example usage of read (conceptual) let fileContent = read "my_data.txt" ``` ### Response - **Success Response (200)**: The script directory path (string) or file content (untyped). ### Response Example ```nim # Current script directory: /path/to/your/script # The content read from the file. ``` ``` -------------------------------- ### Nimja Templating Functions Source: https://github.com/enthus1ast/nimja/blob/master/docs/theindex.html Documentation for functions related to compiling and rendering Nimja templates. ```APIDOC ## COMPILE TEMPLATE FUNCTIONS ### Description These functions are used to compile Nimja templates, either from files or strings, into a renderable format. ### `compileTemplateFile` - **Description**: Compiles a Nimja template from a file. - **Method**: Macro - **Endpoint**: Not applicable (compile-time function) - **Parameters**: - **Path Parameters**: None - **Query Parameters**: None - **Request Body**: None - **Parameters for Macro**: - `path` (static string) - Required - The path to the template file. - `baseDir` (static string) - Optional - The base directory for the template file. - `blockToRender` (static string) - Optional - The specific block within the template to render. - `iter` (static bool) - Optional - If true, iterates over the template. - `varname` (static string) - Optional - The name of the variable to store the result in. - `context` (untyped) - Optional - The context for rendering. ### `compileTemplateStr` - **Description**: Compiles a Nimja template from a string. - **Method**: Macro - **Endpoint**: Not applicable (compile-time function) - **Parameters**: - **Path Parameters**: None - **Query Parameters**: None - **Request Body**: None - **Parameters for Macro**: - `str` (typed) - Required - The template string to compile. - `baseDir` (static string) - Optional - The base directory for the template. - `blockToRender` (static string) - Optional - The specific block within the template to render. - `iter` (static bool) - Optional - If true, iterates over the template. - `varname` (static string) - Optional - The name of the variable to store the result in. - `context` (untyped) - Optional - The context for rendering. ### `tmplf` - **Description**: A shorthand macro to compile a template from a string. - **Method**: Macro - **Endpoint**: Not applicable (compile-time function) - **Parameters**: - **Path Parameters**: None - **Query Parameters**: None - **Request Body**: None - **Parameters for Macro**: - `str` (static string) - Required - The template string. - `baseDir` (static string) - Optional - The base directory. - `blockToRender` (static string) - Optional - The block to render. - `context` (untyped) - Optional - The rendering context. ### `tmpls` - **Description**: A shorthand macro to compile a template from a string, similar to `tmplf`. - **Method**: Macro - **Endpoint**: Not applicable (compile-time function) - **Parameters**: - **Path Parameters**: None - **Query Parameters**: None - **Request Body**: None - **Parameters for Macro**: - `str` (static string) - Required - The template string. - `baseDir` (static string) - Optional - The base directory. - `blockToRender` (static string) - Optional - The block to render. - `context` (untyped) - Optional - The rendering context. ### Request Example ```nim # Example usage of compileTemplateStr let compiledTemplate = compileTemplateStr "Hello, {{ name }}!" # Example usage of tmplf let tmplContent = tmplf "This is a simple template." ``` ### Response - **Success Response (200)**: The compiled template object (untyped). ### Response Example ```nim # The compiled template is an untyped object that can be rendered. # Rendering examples would depend on the specific compilation context. ``` ``` -------------------------------- ### Importing Nimja Macros from Files Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Illustrates how to import macros and procs from one Nimja template file into another using the `importnimja` directive. It also emphasizes the best practice of using `"whitespacecontrol"` for procs. ```nimja {% importnimja "myMacros.nimja" %} ``` -------------------------------- ### Simple String Template Rendering (Nim) Source: https://github.com/enthus1ast/nimja/blob/master/docs/nimja/parser.html A macro for rendering a Nimja template from a string with basic options. It supports specifying a base directory, a particular block to render, and a context object for variable substitution. This is a simpler alternative to `compileTemplateStr` for straightforward string-based templating. ```nim macro tmplf*(str: static string; baseDir: static string = ""; blockToRender: static string = ""; context: untyped = nil): string macro tmpls*(str: static string; baseDir: static string = ""; blockToRender: static string = ""; context: untyped = nil): string ``` -------------------------------- ### Shorthand Nimja Template Rendering (tmpls/tmplf) Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Presents `tmpls` and `tmplf` as convenient shorthands for `compileTemplateStr` and `compileTemplateFile`, respectively. These are useful when a full procedure definition is not needed for simple template rendering. ```nim let leet = 1337 echo tmpls("foo {{leet}}") echo tmplf("templates" / "myfile.nimja", baseDir = getScriptDir()) ``` -------------------------------- ### Nimja Partial Template: Menu Navigation Source: https://github.com/enthus1ast/nimja/blob/master/readme.md A simple Nimja partial template (`partials/_menu.nimja`) that defines a basic navigation menu with a link to the index page. Partial templates are reusable components that can be imported into other Nimja templates. ```twig index ``` -------------------------------- ### Nimja Template Rendering with Dynamic Data Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Demonstrates how to render Nimja templates with dynamic data. The `index` procedure renders `index.nimja` using a dynamic variable `foos`, while `detail` renders `detail.nimja` using an `id` parameter. Both procedures utilize `compileTemplateFile` for rendering, specifying the template file and the base directory for template resolution. ```nim import nimja import os # for `/` proc index*(): string {.exportc, dynlib.} = var foos = 1351 # change me i'm dynamic :) compileTemplateFile("templates/index.nimja", baseDir = getScriptDir()) proc detail*(id: string): string {.exportc, dynlib.} = compileTemplateFile("templates/detail.nimja", baseDir = getScriptDir()) ``` -------------------------------- ### Compile Nimja Template File Source: https://github.com/enthus1ast/nimja/blob/master/docs/nimja.html Compiles a Nimja template from a file. It requires the path to the template file, the directory of the script, the name of the template, and a boolean for compilation output type. Returns the compiled template as a string. Dependencies include file system access and the nimja parser. ```nim proc compileTemplateFile*(templateFile, scriptDir, tmplName: string, compileToString: bool = false): string | NimjaAST = nimja/parser.compileTemplateFile(templateFile, scriptDir, tmplName, compileToString) ``` -------------------------------- ### Nimja Cycle Utility Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Shows how to use the cycle utility within a loop to alternate CSS classes or values. ```twig {% for (loop, row) in rows.loop() %}
  • {{ row }}
  • {% endfor %} ``` -------------------------------- ### Rendering Specific Nimja Template Blocks (compileTemplateFile) Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Demonstrates rendering a specific block from a Nimja template file using `compileTemplateFile`. The `blockToRender` parameter ensures that only the content within the specified block is processed. ```nim proc render(): string = compileTemplateFile("template.nimja", blockToRender = "foo", baseDir = getScriptDir()) ``` -------------------------------- ### Nimja Debugging Commands Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Lists various Nim compiler commands used for debugging Nimja. These commands enable features like dumping the Abstract Syntax Tree (AST) in different formats, disabling the cache, and controlling string pre-allocation and condensation, providing insights into the template compilation and execution process. ```bash nim c -d:dumpNwtAst -r yourfile.nim # <-- dump NwtAst nim c -d:dumpNwtAstPretty -r yourfile.nim # <-- dump NwtAst as pretty json nim c -d:nwtCacheOff -r yourfile.nim # <-- disables the NwtNode cache nim c -d:noPreallocatedString -r yourfile # <-- do not preallocate the output string nim c -d:noCondenseStrings -r yourfile.nim # <-- disables string condense see #12 nim c -d:dumpNwtMacro -r yourfile.nim # <-- dump generated Nim macros ``` -------------------------------- ### Rendering Specific Nimja Template Blocks (tmpls) Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Shows how to use the `tmpls` function to render a specific block from a Nimja template string. The `blockToRender` parameter specifies which block should be processed and returned. ```nim tmpls("not rendered{% block foo %}foo{% endblock %}", blockToRender = "foo", baseDir = getScriptDir()) ``` -------------------------------- ### Procedures Source: https://github.com/enthus1ast/nimja/blob/master/src/nimja/htmldocs/nimjautils.html Details the 'cycle' procedure for cycling through elements within a loop. ```APIDOC ## Procedures ### cycle[T] **Description**: Cycles through a given array of elements, returning one element per iteration. **Parameters**: - `loop` (Loop) - The current loop state. - `elems` (openArray[T]) - An open array of elements to cycle through. **Returns**: The element from `elems` corresponding to the current loop iteration, cycling back to the beginning when the end is reached. **Usage Example**: ```nim {% for loop, row in rows.loop() %}
  • {{ row }}
  • {% endfor %} ``` ``` -------------------------------- ### Compile Nim Template File with Base Directory Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Demonstrates the usage of `compileTemplateFile` to compile a Nimja template from a specified file path. It utilizes `getScriptDir()` to correctly resolve the base directory for the template file. ```nim import os # for `/` proc myRenderProc(someParam: string): string = compileTemplateFile("myFile.html", baseDir = getScriptDir()) echo myRenderProc("test123") ``` -------------------------------- ### Nimja Utility Functions Source: https://github.com/enthus1ast/nimja/blob/master/docs/theindex.html Documentation for utility functions provided by the Nimja project. ```APIDOC ## NIMJAUTILS FUNCTIONS ### Description This section details the utility functions available in the `nimjautils` module, covering string manipulation, file handling, and looping constructs. ### `?` (template) - **Description**: A template for a specific purpose (details not fully specified in source). Likely related to template interpolation or rendering. - **Module**: nimjautils - **Signature**: `template ?(con, body: untyped): untyped` ### `|` (macro) - **Description**: A macro that likely concatenates or combines two untyped arguments into a string. - **Module**: nimjautils - **Signature**: `macro `|`(aa, bb: untyped): string` ### `~` (template) - **Description**: A template that likely performs string concatenation or manipulation on two untyped arguments. - **Module**: nimjautils - **Signature**: `template `~`(aa, bb: untyped): string` ### `allowedCharsInSlug` (const) - **Description**: A constant defining the allowed characters for slugification. - **Module**: nimjautils - **Signature**: `const allowedCharsInSlug` ### `cycle` (proc) - **Description**: Cycles through elements in an array, returning the next element in the sequence. - **Module**: nimjautils - **Signature**: `proc cycle[T](loop: Loop; elems: openArray[T]): T` - **Parameters**: - `loop` (Loop) - The current loop state. - `elems` (openArray[T]) - The array of elements to cycle through. ### `includeRaw` (proc) - **Description**: Reads the content of a file and returns it as a string. - **Module**: nimjautils - **Signature**: `proc includeRaw(path: string): string` - **Parameters**: - `path` (string) - The path to the file. ### `includeRawStatic` (proc) - **Description**: Reads the content of a file at compile time and returns it as a string. - **Module**: nimjautils - **Signature**: `proc includeRawStatic(path: static string): string` - **Parameters**: - `path` (static string) - The compile-time path to the file. ### `includeStaticAsDataurl` (proc) - **Description**: Reads a file at compile time and returns its content as a data URL. - **Module**: nimjautils - **Signature**: `proc includeStaticAsDataurl(path: static string; mimeOverride: static string = ""): string` - **Parameters**: - `path` (static string) - The compile-time path to the file. - `mimeOverride` (static string) - Optional MIME type override. ### `Loop` (object) - **Description**: An object representing the state of a loop iteration. - **Module**: nimjautils ### `loop` (iterator) - **Description**: An iterator that provides both the loop state and the current element for an array. - **Module**: nimjautils - **Signature**: `iterator loop[T](a: openArray[T]): tuple[loop: Loop[T], val: T]` - **Parameters**: - `a` (openArray[T]) - The array to iterate over. ### `Loopable` (type) - **Description**: A type alias for elements that can be used in a loop. - **Module**: nimjautils ### `nl2br` (proc) - **Description**: Converts newline characters in a string to HTML `
    ` tags. - **Module**: nimjautils - **Signature**: `proc nl2br(str: string; keepNl = true): string` - **Parameters**: - `str` (string) - The input string. - `keepNl` (bool) - If true, preserves the original newline characters. ### `slugify` (proc) - **Description**: Converts a string into a URL-friendly slug. - **Module**: nimjautils - **Signature**: `proc slugify(str: string; seperator = "-"; allowedChars = allowedCharsInSlug): string` - **Parameters**: - `str` (string) - The string to slugify. - `seperator` (string) - The separator to use between words (default: "-"). - `allowedChars` (string) - The set of allowed characters in the slug. ### `spaceless` (proc) - **Description**: Removes whitespace from a string, often used for HTML output. - **Module**: nimjautils - **Signature**: `proc spaceless(str: string): string` - **Parameters**: - `str` (string) - The input string. ### `truncate` (proc) - **Description**: Truncates a string to a specified length, optionally preserving words and adding a suffix. - **Module**: nimjautils - **Signature**: `proc truncate(str: string; num: Natural; preserveWords = true; suf = "..."): string` - **Parameters**: - `str` (string) - The string to truncate. - `num` (Natural) - The maximum length of the truncated string. - `preserveWords` (bool) - If true, truncates at a word boundary. - `suf` (string) - The suffix to append if truncation occurs. ### Request Example ```nim # Example usage of slugify let slug = slugify("My Awesome Title!") # "my-awesome-title" # Example usage of nl2br let htmlString = nl2br("Line 1\nLine 2") # "Line 1
    Line 2" # Example usage of loop iterator for item in loop([1, 2, 3]): echo "Loop index: ", item.loop.index, " Value: ", item.val ``` ### Response - **Success Response (200)**: Varies depending on the function (string, object, etc.). ### Response Example ```nim # "my-awesome-title" # "Line 1
    # Line 2" # Loop index: 0 Value: 1 # Loop index: 1 Value: 2 # Loop index: 2 Value: 3 ``` ``` -------------------------------- ### Nimja Lexer and Parser Tokens Source: https://github.com/enthus1ast/nimja/blob/master/docs/theindex.html Documentation for token types used in Nimja's lexer and parser. ```APIDOC ## LEXER AND PARSER TOKENS ### Description This section describes the token kinds used by the Nimja lexer, which are fundamental for parsing template strings. ### `NwtComment` (NwtTokenKind) - **Description**: Represents a comment token within the Nimja template. - **Module**: nimja/lexer ### `NwtEval` (NwtTokenKind) - **Description**: Represents an evaluation token (e.g., `{{ ... }}`) within the Nimja template. - **Module**: nimja/lexer ### `NwtNone` (NwtTokenKind) - **Description**: Represents an unknown or none token type. - **Module**: nimja/lexer ### `NwtString` (NwtTokenKind) - **Description**: Represents a string literal token within the Nimja template. - **Module**: nimja/lexer ### `NwtTokenKind` (enum) - **Description**: An enumeration of the different token kinds recognized by the Nimja lexer. - **Module**: nimja/lexer ### `NwtVariable` (NwtTokenKind) - **Description**: Represents a variable token (e.g., `{{ variable }}`) within the Nimja template. - **Module**: nimja/lexer ### `Token` (object) - **Description**: Represents a single token with its kind and value. - **Module**: nimja/lexer ### Request Example ```nim # Example of lexing a string (conceptual) for token in lex("Hello {{ name }}!"): echo token.kind, ": ", token.value ``` ### Response - **Success Response (200)**: The lexer yields `Token` objects. ### Response Example ```nim # NwtString: Hello # NwtVariable: name # NwtString: ! ``` ``` -------------------------------- ### Nimja Template: Extending Base Layout Source: https://github.com/enthus1ast/nimja/blob/master/readme.md This Nimja template (`index.nimja`) demonstrates template inheritance by extending a master template (`_master.nimja`). It defines blocks for content and footer, includes dynamic content generation with loops and random element selection, and imports partial templates for user display. The template also showcases the use of `const` for local variables within the template and `var` for mutable variables. ```twig {% extends partials/_master.nimja%} {# extends uses the master.nimja template as the "base". All the `block`s that are defined in the master.nimja are filled with blocks from this template. If the templates extends another, all content HAVE TO be in a block. blocks can have arbitrary names extend must be the first token in the template, only comments `{# Some foo #}` and strings are permitted to come before it. #} {% block content %} {# A random loop to show off. #} {# Data is defined here for demo purpose, but could come frome database etc.. #}

    Random links

    {% const links = [ (title: "google", target: "https://google.de"), (title: "fefe", target: "https://blog.fefe.de")] %} {% for (ii, item) in links.pairs() %} {{ii}} This is a link to: {{item.title}}
    {% endfor %}

    Members

    {# `users` was a param to the `renderIndex` proc #} {% for (idx, user) in users.pairs %} {% importnimja "./partials/_user.nimja" %}
    {% endfor %} {% endblock %} {% block footer %} {# we can call arbitraty nim code in the templates. Here we pick a random user from users. #} {% var user = users.sample() %} {# imported templates have access to all variables declared in the parent. So `user` is usable in "./partials/user.nimja" #} This INDEX was presented by.... {% importnimja "./partials/_user.nimja" %} {% endblock footer %} {# the 'footer' in endblock is completely optional #} ``` -------------------------------- ### Read File Content at Compile or Run Time (Nim) Source: https://github.com/enthus1ast/nimja/blob/master/docs/nimja/sharedhelper.html The read function acts as an internal helper for file operations. At compile time, it utilizes staticRead, while at runtime, it uses readFile. ```nim template read(path: untyped): untyped ``` -------------------------------- ### Rendering Specific Nimja Template Blocks (tmplf) Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Illustrates rendering a specific block from a Nimja template file using the `tmplf` function. This is useful for dynamic content updates, such as with HTMX, where only a portion of the page needs to be re-rendered. ```nim tmplf("template.nimja", blockToRender = "foo", baseDir = getScriptDir()) ``` -------------------------------- ### Compile Nimja Template from File (Nim) Source: https://github.com/enthus1ast/nimja/blob/master/docs/nimja/parser.html Compiles a Nimja template from a specified file path. Supports optional base directory, block rendering, iteration for streaming, a variable name for appending, and context overrides for variables within the template. The `iter` parameter enables iterator usage for memory efficiency with large templates. ```nim macro compileTemplateFile*(path: static string; baseDir: static string = ""; blockToRender: static string = ""; iter: static bool = false; varname: static string = "result"; context: untyped = nil): untyped Compiles a Nimja template from a file. proc yourFunc(yourParams: bool): string = compileTemplateFile(getScriptDir() / "relative/path.nimja) echo yourFunc(true) If iter = true then the macro can be used in an iterator body this could be used for streaming templates, or to save memory when a big template is rendered and the http server can send data in chunks. iterator yourIter(yourParams: bool): string = compileTemplateFile(getScriptDir() / "relative/path.nimja, iter = true) for elem in yourIter(true): echo elem varname specifies the variable that is appended to. A context can be supplied to the compileTemplateFile (also compileTemplateStr), to override variable names: block: type Rax = object aa: string bb: float var rax = Rax(aa: "aaaa", bb: 13.37) var foo = 123 proc render(): string = compileTemplateFile(getScriptDir() / "myTemplate.nimja", {node: rax, baa: foo}) ``` -------------------------------- ### Compile Nimja Template String Source: https://github.com/enthus1ast/nimja/blob/master/docs/nimja.html Compiles a Nimja template provided as a string. It takes the template string, a name for the template, and a boolean indicating whether to compile as a string or an AST. Returns the compiled template. Dependencies include the nimja parser. ```nim proc compileTemplateStr*(template: string, tmplName: string, compileToString: bool = false): string | NimjaAST = nimja/parser.compileTemplateStr(template, tmplName, compileToString) ``` -------------------------------- ### Nimja Template Case Statement Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Demonstrates the `case` statement in Nimja, which functions similarly to Nim's `case` statement for exhaustive conditional checking. It ensures all possible cases are handled, otherwise generating a compile-time error. ```twig {%- case str -%} {%- of "foo" -%} foo {%- of "baa" -%} baa {%- of "baz" -%} baz {%- else -%} nothing {%- endcase -%} ``` -------------------------------- ### Nimja Condition Shorthand Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Demonstrates the shorthand syntax for conditional rendering in Nimja templates. It uses a ternary-like structure within the template to conditionally apply text. ```nim proc foo(isDisabled: bool): string = compileTemplateStr("{% ?isDisabled: \"disabled\" %}") check "disabled" == foo(true) check "" == foo(false) ``` -------------------------------- ### Template for Conditional Execution Source: https://github.com/enthus1ast/nimja/blob/master/docs/nimja/nimjautils.html A template `?` that executes a body of code only if a condition is met. This is a Nim template for conditional logic. ```nim template `?`(con, body: untyped): untyped ``` -------------------------------- ### Nimja Template Compilation with Base Directory Parameter Source: https://github.com/enthus1ast/nimja/blob/master/readme.md Shows the evolution of Nimja's `compileTemplateFile` and related functions to include a `baseDir` parameter. This parameter is crucial for resolving imported templates and components correctly, especially when templates are organized in subdirectories or imported from other modules, as highlighted in version 0.9.0 changelog. ```nim compileTemplateStr("{{importnimja \"some/template.nimja\"}}", baseDir = getScriptDir()) tmpls("{{importnimja \"some/template.nimja\"}}", baseDir = getScriptDir()) compileTemplateFile("some/template.nimja", baseDir = getScriptDir()) tmpls("some/template.nimja", baseDir = getScriptDir()) ``` -------------------------------- ### Nimja Master Template: Base HTML Structure Source: https://github.com/enthus1ast/nimja/blob/master/readme.md This Nimja template (`partials/_master.nimja`) serves as the base layout for other templates. It defines the fundamental HTML structure, including head, body, styles, and footer sections. It also declares a master-level variable `aVarFromMaster` and imports a menu partial (`_menu.nimja`). Blocks like `content` and `footer` are defined to be filled by child templates. ```twig {# This template is later expanded from the index.nimja template. All blocks are filled by the blocks from index.nimja Variables are also useable. #} {{title}} {# The master can declare a variable that is later visible in the child template #} {% var aVarFromMaster = "aVarFromMaster" %} {# We import templates to keep the master small #} {% importnimja "partials/_menu.nimja" %}

    {{title}}

    {# This block is filled from the child templates #} {%block content%}{%endblock%} {# If the block contains content and is NOT overwritten later. The content from the master is rendered #} {% block onlyMasterBlock %}Only Master Block{% endblock %} ``` -------------------------------- ### Compile Nimja Template from String (Nim) Source: https://github.com/enthus1ast/nimja/blob/master/docs/nimja/parser.html Compiles a Nimja template directly from a string. It accepts optional parameters for base directory, specific block rendering, iteration for streaming, the name of the variable to append to, and a context for variable overrides. The `iter` parameter is useful for generating template output in chunks. ```nim macro compileTemplateStr*(str: typed; baseDir: static string = ""; blockToRender: static string = ""; iter: static bool = false; varname: static string = "result"; context: untyped = nil): untyped Compiles a Nimja template from a string. proc yourFunc(yourParams: bool): string = compileTemplateStr("{%if yourParams%}TRUE{%endif%}") echo yourFunc(true) If iter = true then the macro can be used in an iterator body this could be used for streaming templates, or to save memory when a big template is rendered and the http server can send data in chunks. iterator yourIter(yourParams: bool): string = compileTemplateStr("{%for idx in 0 .. 100%}{{idx}}{%endfor%}", iter = true) for elem in yourIter(true): echo elem varname specifies the variable that is appended to. A context can be supplied to the compileTemplateStr (also compileTemplateFile), to override variable names: block: type Rax = object aa: string bb: float var rax = Rax(aa: "aaaa", bb: 13.37) var foo = 123 proc render(): string = compileTemplateStr("{{node.bb}}{{baa}}", {node: rax, baa: foo}) ``` -------------------------------- ### Include File Content Literally (Compile-time) Source: https://github.com/enthus1ast/nimja/blob/master/docs/nimja/nimjautils.html The 'includeRawStatic' procedure includes the content of a file literally at compile time. This is efficient for embedding static assets or configuration files directly into the executable. ```nim proc includeRawStatic(path: static string): string ``` -------------------------------- ### Include File Content Literally (Runtime) Source: https://github.com/enthus1ast/nimja/blob/master/docs/nimja/nimjautils.html The 'includeRaw' procedure reads the content of a specified file at runtime and returns it as a string. This is useful for including plain text or markdown content directly into templates. ```nim proc includeRaw(path: string): string ```