### Install Tim Engine via Package Managers Source: https://context7.com/openpeeps/tim/llms.txt Instructions for installing the Tim Engine library using Nimble for Nim projects or npm for Node.js environments. ```bash # Install for Nim projects nimble install tim # Install for Node.js projects npm install @openpeeps/tim ``` -------------------------------- ### Initialize and Configure Tim Engine in Nim Source: https://context7.com/openpeeps/tim/llms.txt Demonstrates how to initialize the Tim engine, define route handlers with custom response templates, and start a web server using the engine. ```nim var timl = newTim( src = "templates", output = "storage", basepath = getCurrentDir(), globalData = %*{ "year": 2024, "siteName": "My Mummy App" } ) timl.precompile() template resp(req: Request, view: string, layout = "base", local = newJObject(), code = 200) = var headers: HttpHeaders headers["Content-Type"] = "text/html" {.gcsafe.}: local["path"] = %*(req.path) let output = timl.render(view, layout, local) req.respond(code, headers, output) proc indexHandler(req: Request) = req.resp("index", local = %*{ "meta": { "title": "Welcome to Tim!" } }) var router: Router router.get("/", indexHandler) let server = newServer(router) server.serve(Port(8081)) ``` -------------------------------- ### Initialize Tim Engine Instance Source: https://context7.com/openpeeps/tim/llms.txt Creates a new Tim Engine instance by defining source/output directories and global data configurations. This setup is required before performing any template compilation or rendering. ```nim import tim import std/json let timl = newTim( src = "templates", output = "storage", basepath = getCurrentDir(), target = TargetSource.tsHtml, globalData = %*{ "year": 2024, "siteName": "My Website", "stylesheets": [ {"type": "stylesheet", "src": "https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css"} ] } ) timl.precompile() ``` -------------------------------- ### Tim CLI Transpilation Commands Source: https://context7.com/openpeeps/tim/llms.txt Provides examples of using the Tim CLI to transpile templates into various target languages and manage build configurations. ```bash tim src template.timl --ext=js tim src template.timl --ext=php tim src template.timl --ext=py tim src template.timl --data='{"title":"Hello","count":5}' tim ast template.timl ``` -------------------------------- ### Install Tim Template Engine via npm Source: https://github.com/openpeeps/tim/blob/rewrite/bindings/node/tim/README.md This command installs the Tim template engine package using npm, the Node Package Manager. This is the primary method for integrating Tim into JavaScript projects. ```bash npm install @openpeeps/tim ``` -------------------------------- ### Tim CLI Package Management Source: https://context7.com/openpeeps/tim/llms.txt Covers common CLI commands for initializing, installing, and managing template packages within a Tim project. ```bash tim init mypackage tim install username/package-name tim develop ./path/to/local-package tim remove package-name ``` -------------------------------- ### Tim Markup Language Example Source: https://github.com/openpeeps/tim/blob/rewrite/bindings/node/tim/README.md This snippet demonstrates the basic syntax of the Tim markup language for creating HTML structures. It showcases element nesting, class and ID attributes, and text content. ```timl div.container > div.row > div.col-lg-7.mx-auto h1.display-3.fw-bold: "Tim is Awesome" a href="https://github.com/openpeeps/tim" title="This is hot!": "Check Tim on GitHub" ``` -------------------------------- ### Integrate Tim Engine with Node.js Source: https://context7.com/openpeeps/tim/llms.txt Shows how to initialize the Tim engine and use it for server-side template rendering within a Node.js HTTP server. ```javascript const path = require('path') const http = require('http') const tim = require('@openpeeps/tim') // Initialize Tim Engine with template directory tim.init( "templates", // Source templates directory "storage", // Output/cache directory path.resolve(__dirname), // Base path false, // Debug mode 2 // Indentation level ) // Precompile templates with global data tim.precompile({ data: { year: new Date().getFullYear(), siteName: "My Application", stylesheets: [ { type: "stylesheet", src: "https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" } ] }, watchout: { enable: true, port: 6502, delay: 300 } }) // Create HTTP server with Tim rendering http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html') res.setHeader('charset', 'utf-8') if (req.url === '/') { res.writeHead(200) res.end(tim.render("index", "base", { meta: { title: "Home Page" }, path: req.url })) } else if (req.url === '/about') { res.writeHead(200) res.end(tim.render("about", "secondary", { meta: { title: "About Us" }, path: req.url })) } else { res.writeHead(404) res.end(tim.render("error", "base", { meta: { title: "Not Found", msg: "Page not found" }, path: req.url })) } }).listen(3000, 'localhost', () => { console.log('Server running on http://localhost:3000') }) ``` -------------------------------- ### Extend Tim Engine with Custom Procedures Source: https://context7.com/openpeeps/tim/llms.txt Shows how to register custom Nim procedures into the Tim engine's user script, allowing them to be invoked directly within template files. ```nim timl.userScript.addProc( name = "formatCurrency", params = @[paramDef("amount", ttyFloat), paramDef("currency", ttyString)], returnTy = ttyString, impl = proc(args: StackView): Value = let amount = args[0].floatVal let currency = args[1].stringVal[] result = initValue(currency & " " & $amount) ) timl.precompile() ``` -------------------------------- ### Declare Variables and Constants in Tim Source: https://context7.com/openpeeps/tim/llms.txt Demonstrates how to define compile-time constants and runtime variables using 'const' and 'var'. It also shows how to inject these values directly into HTML elements. ```timl const logo = "https://example.com/logo.png" const heading = "This is Tim!" var counter = 0 var items = ["one", "two", "three"] h1: $heading img src=$logo alt="Logo" ``` -------------------------------- ### Manage Layouts, Views, and Partials Source: https://context7.com/openpeeps/tim/llms.txt Describes the modular structure of Tim Engine using layouts for page shells, views for content, and partials for reusable components via the '@include' directive. ```timl html head @include "meta/head" body @view @include "footer" ``` -------------------------------- ### Define HTML Elements with Tim Syntax Source: https://context7.com/openpeeps/tim/llms.txt Demonstrates the indentation-based syntax for defining HTML structures, including CSS-style class and ID selectors for concise markup generation. ```timl h1: "Welcome to Tim Engine" div.container > div.row > div.col-lg-7.mx-auto h1.display-3.fw-bold: "Tim is Awesome" p.lead.text-muted: "Fast, compiled, clean syntax" div#main-content.wrapper section.content article.post: "Article content here" nav.navbar ul.nav li.nav-item a.nav-link href="/": "Home" ``` -------------------------------- ### Integrate Tim Engine with Nim Mummy Source: https://context7.com/openpeeps/tim/llms.txt Initializes the Tim engine for use within a Nim web application using the Mummy framework. ```nim import std/[os, json] import pkg/[mummy, mummy/routers] import tim ``` -------------------------------- ### Iterate with Loops Source: https://context7.com/openpeeps/tim/llms.txt Explains how to iterate over arrays and JSON objects using the 'for' loop syntax. Supports simple arrays, object properties, and nested structures. ```timl for $item in $items: li: $item for $category in $this.categories: div.category h3: $category.name ul for $product in $category.products: li: $product.name ``` -------------------------------- ### Render Templates with Layouts and Views Source: https://context7.com/openpeeps/tim/llms.txt Renders a view template wrapped in a layout, allowing for local data injection via the $this variable. This is the standard method for generating full-page HTML responses. ```nim import tim import std/json let timl = newTim("templates", "storage", getCurrentDir()) timl.precompile() let html = timl.render( view = "index", layout = "base", data = %*{ "meta": { "title": "Welcome to Tim Engine" }, "user": { "name": "John Doe", "email": "john@example.com" } } ) echo html ``` -------------------------------- ### Utilize System Functions in Tim Source: https://context7.com/openpeeps/tim/llms.txt Provides core system capabilities including type conversion, JSON parsing, file I/O, debugging, and HTTP requests. ```timl // Type inspection var value = 42 echo type($value) // "int" // Type conversion var intVal = toInt(3.14) // 3 var floatVal = toFloat(42) // 42.0 var strVal = toString(100) // "100" // JSON operations var jsonStr = '{"name": "Tim", "version": 2}' var data = parseJSON($jsonStr) echo $data.name // "Tim" // Load JSON from file const config = loadJSON("./config.json") echo $config.settings.theme // Fetch remote JSON const apiData = remoteJSON("https://api.example.com/data") echo $apiData.status // HTTP status echo $apiData.content // Response body as JSON // Object key checking if hasKey($data, "name"): p: "Name exists: " & $data.name // Get object keys as array var keys = toKeys($this.settings) // Debug output echo "Debug message" echo $this.user echo $config // Assertions (for testing) assert $value == 42 assert len($fruits) > 0 // Numeric operations var count = 0 inc($count) // count = 1 dec($count) // count = 0 // File operations var content = readFile("./data.txt") writeFile("./output.txt", "Generated content") // Delay execution sleep(1000) // Sleep for 1000ms ``` -------------------------------- ### Perform String Manipulation in Tim Source: https://context7.com/openpeeps/tim/llms.txt Demonstrates built-in string functions including case conversion, searching, replacement, Base64 encoding, parsing, and formatting. These functions rely on the std/strings module. ```timl @import "std/strings" var text = "Tim is Awesome" // Case conversion var upper = $text.toUpper // "TIM IS AWESOME" var lower = $text.toLower // "tim is awesome" // String searching if $text.startsWith("Tim"): p: "Text starts with Tim" if $text.endsWith("some"): p: "Text ends with 'some'" if $text.contains("Awesome"): p: "Text contains 'Awesome'" // String replacement var replaced = $text.replace("Awesome", "Great!") // "Tim is Great!" // Base64 encoding/decoding var encoded = encode("Hello World") // Base64 encoded string var decoded = decode($encoded) // "Hello World" // String parsing var num = parseInt("100") // 100 var float = parseFloat("99.99") // 99.99 var bool = parseBool("true") // true // String formatting var formatted = format("$1 is $2", ["Tim", "Fast"]) // "Tim is Fast" ``` -------------------------------- ### Apply Attributes to Tim Elements Source: https://context7.com/openpeeps/tim/llms.txt Shows how to define HTML attributes inline, including support for static values, dynamic variables, and complex elements like SVG. ```timl a href="https://github.com/openpeeps/tim" title="Check Tim on GitHub" span: "Visit Repository" img src="logo.png" alt="Tim Engine Logo" width="200px" const logoUrl = "https://example.com/logo.png" img src=$logoUrl alt="Dynamic Logo" svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" fill="none" path d="M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87" ``` -------------------------------- ### Implement Conditional Rendering Source: https://context7.com/openpeeps/tim/llms.txt Shows the use of 'if', 'else if', and 'else' blocks to conditionally render HTML elements based on local data or boolean expressions. ```timl if $this.isLoggedIn: p: "Welcome back, " & $this.user.name else: p: "Please log in" if $this.role == "admin": div.admin-panel h2: "Admin Dashboard" ``` -------------------------------- ### Render Standalone Views Source: https://context7.com/openpeeps/tim/llms.txt Renders a view template directly without a layout wrapper. This is ideal for partials, components, or AJAX-based dynamic content updates. ```nim import tim import std/json let timl = newTim("templates", "storage", getCurrentDir()) timl.precompile() let partialHtml = timl.renderView( view = "components/card", data = %*{ "title": "Product Card", "price": 29.99, "inStock": true } ) echo partialHtml ``` -------------------------------- ### Manage Arrays in Tim Source: https://context7.com/openpeeps/tim/llms.txt Covers array operations such as adding, removing, searching, inserting, joining, and deduplicating elements. Requires the std/arrays module. ```timl @import "std/arrays" var fruits = ["apple", "banana", "cherry"] // Check if array contains value if $fruits.contains("banana"): p: "We have bananas!" // Add item to array $fruits.add("orange") // Find index of item (-1 if not found) var index = $fruits.find("cherry") // Returns 2 // Delete item by index $fruits.delete(0) // Removes "apple" // Insert at specific position $fruits.insert("mango", 1) // Join array to string var list = $fruits.join // "banana, mango, cherry, orange" // Remove duplicates var numbers = [1, 2, 2, 3, 3, 3] $numbers.dedup // [1, 2, 3] // Get array length and high index var count = len($fruits) // 4 var lastIdx = high($fruits) // 3 ``` -------------------------------- ### Transpile to Client-Side JavaScript Source: https://context7.com/openpeeps/tim/llms.txt Utilizes the '@client' directive to define sections of code that are transpiled into JavaScript for dynamic browser-side rendering, targeted at specific DOM elements. ```timl @client target="#clickable" div.dynamic-content span: "Click for more info" @end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.