Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Jinja Php Laravel Package

codewithkyrian/jinja-php

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require codewithkyrian/jinja-php
    

    No additional dependencies required.

  2. First Use Case: Render a simple ML chat template:

    use CodeWithKyrian\Jinja\Template;
    
    $template = new Template("{{ bos_token }}{{ message.content }}");
    $rendered = $template->render([
        'bos_token' => '<s>',
        'message' => ['content' => 'Hello, world!']
    ]);
    
  3. Where to Look First:


Implementation Patterns

Core Workflows

1. Dynamic Template Rendering

// In a Laravel controller
public function renderChatTemplate(Request $request) {
    $template = new Template(file_get_contents('resources/templates/chat.jinja'));
    $data = [
        'messages' => $request->messages,
        'bos_token' => config('app.bos_token'),
    ];
    return response()->json(['output' => $template->render($data)]);
}

2. Reusable Macros

// Define macros in a template file
$template = new Template(<<<'JINJA'
    {% macro formatMessage(message) %}
        <div class="message {{ message.role }}">
            {{ message.content }}
        </div>
    {% endmacro %}

    {% for message in messages %}
        {{ formatMessage(message) }}
    {% endfor %}
JINJA);

// Render with data
$rendered = $template->render(['messages' => [...]]);

3. Filter Chaining

// Process text in templates
$template = new Template("{{ text|upper|replace('HELLO', 'Hi') }}");
$rendered = $template->render(['text' => 'hello world']);

4. Integration with Laravel Views

// Create a custom view resolver
app()->resolving(View::class, function () {
    View::addExtension('jinja', function ($path, array $data) {
        $template = new Template(file_get_contents($path));
        return $template->render($data);
    });
});

// Usage in Blade
@jinja('templates/email.jinja', ['user' => $user])

5. Custom Filters

use CodeWithKyrian\Jinja\Environment;

$env = new Environment();
$env->addFilter('custom_filter', function ($value) {
    return strtoupper($value) . '!';
});

$template = new Template("{{ text|custom_filter }}");
$rendered = $template->render(['text' => 'hello'], $env);

Gotchas and Tips

Pitfalls

  1. Negative Array Indexing:

    • Uses Python-style indexing (messages[-1]), which may confuse developers used to PHP's end($array).
    • Fix: Document this behavior in your team's style guide.
  2. Boolean Literals:

    • Accepts both true/false and True/False (case-insensitive).
    • Gotcha: null is not falsy; use none or None for null literals.
  3. String Concatenation:

    • Uses ~ operator ({{ "a" ~ "b" }}), not PHP's ..
    • Tip: Escape ~ in raw strings by doubling: {{ "a~~b" }}.
  4. Loop Variables:

    • loop.index0 starts at 0 (like Python), not 1 (like PHP's array_key_first).
    • Example:
      {% for item in items %}
          {{ loop.index }}  {# 1-based #}
          {{ loop.index0 }} {# 0-based #}
      {% endfor %}
      
  5. Template Inheritance:

    • Not supported. Use Laravel's Blade inheritance for shared layouts.
  6. Custom Functions:

    • Not supported. Register filters instead for reusable logic.

Debugging Tips

  1. Enable Debug Mode:

    $template = new Template($source);
    $template->setDebug(true); // Shows parsing errors with line numbers
    
  2. Inspect Parsed AST:

    $ast = $template->parse();
    print_r($ast->dump()); // Dump the Abstract Syntax Tree
    
  3. Common Errors:

    • Undefined variable: Ensure all variables in templates exist in $args.
    • SyntaxError: Validate templates against Jinja spec.
    • Call to undefined function: Use filters or macros instead of custom functions.

Extension Points

  1. Custom Filters:

    $env->addFilter('slugify', function ($value) {
        return Str::slug($value);
    });
    
  2. Custom Transformers:

    $env->addTransformer('generation', function ($value) {
        return str_replace(['<s>', '</s>'], ['[START]', '[END]'], $value);
    });
    
  3. Pre/Post-Processing:

    $template->setPreProcessor(function ($source) {
        return str_replace('{{{', '{{', $source); // Custom tag support
    });
    
  4. Environment Configuration:

    $env = new Environment();
    $env->setStrictVariables(true); // Throw errors for undefined variables
    $env->setAutoescape(false); // Disable HTML escaping
    

Performance Considerations

  1. Cache Parsed Templates:

    $cacheKey = 'template_' . md5($templateSource);
    if (cache()->has($cacheKey)) {
        $rendered = cache()->get($cacheKey);
    } else {
        $rendered = $template->render($data);
        cache()->put($cacheKey, $rendered, now()->addHours(1));
    }
    
  2. Avoid Overusing Macros:

    • Macros add slight overhead. Use them for complex, reusable logic only.
  3. Minimize Filters:

    • Chain filters sparingly (e.g., {{ text|upper|title }} is less efficient than {{ (text|upper)|title }}).
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity