All Projects → Brain-WP → Context

Brain-WP / Context

Licence: MIT license
WordPress package to build a "context" (based on a query object) suiteable to be bassed to templates..

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to Context

htmldoom
An intuitive, high performance HTML rendering framework
Stars: ✭ 36 (+100%)
Mutual labels:  template-engine
Panda
Create view hierarchies declaratively.
Stars: ✭ 69 (+283.33%)
Mutual labels:  hierarchy
escapevelocity
A subset reimplementation of Apache Velocity with a much simpler API.
Stars: ✭ 28 (+55.56%)
Mutual labels:  template-engine
tale-pug
Tale Pug is the popular JavaScript Template Engine Pug, formerly Jade, for PHP!
Stars: ✭ 32 (+77.78%)
Mutual labels:  template-engine
Velocity
🚀Velocity template engine for JavaScript and PHP.
Stars: ✭ 33 (+83.33%)
Mutual labels:  template-engine
JSON-path
Find the path of a key / value in a JSON hierarchy easily.
Stars: ✭ 88 (+388.89%)
Mutual labels:  hierarchy
lua-template
The simplest Lua template engine
Stars: ✭ 33 (+83.33%)
Mutual labels:  template-engine
liquid.cr
Kind of liquid template engine for Crystal [WIP]
Stars: ✭ 64 (+255.56%)
Mutual labels:  template-engine
vpl
Vuejs-syntax like template-engine for Go
Stars: ✭ 19 (+5.56%)
Mutual labels:  template-engine
velvet
A sweet velvety templating package
Stars: ✭ 72 (+300%)
Mutual labels:  template-engine
storybook-chapters
React Storybook Addon for Hierarchical Substories (Chapters)
Stars: ✭ 46 (+155.56%)
Mutual labels:  hierarchy
jinja.dart
Jinja2 template engine port for Dart.
Stars: ✭ 38 (+111.11%)
Mutual labels:  template-engine
micro-template.js
A template engine on JavaScript which like embed js
Stars: ✭ 49 (+172.22%)
Mutual labels:  template-engine
CodegenCS
C# Toolkit for Code Generation (T4 alternative!)
Stars: ✭ 119 (+561.11%)
Mutual labels:  template-engine
ultron-ele
The world’s fastest LMS engine based on Gatsby -- Deliver knowledge with fun!
Stars: ✭ 27 (+50%)
Mutual labels:  template-engine
Kvantum
An intellectual (HTTP/HTTPS) web server with support for server side templating (Crush, Apache Velocity and JTwig)
Stars: ✭ 17 (-5.56%)
Mutual labels:  template-engine
MultiplatformPlayground
Kotlin Multiplatform project in Jetpack Compose & SwiftUI with shared ViewModel layer and File upload
Stars: ✭ 72 (+300%)
Mutual labels:  hierarchy
nornj
More exciting JS/JSX based on Template Engine, support control flow tags, custom directives, two-way binding, filters and custom operators.
Stars: ✭ 97 (+438.89%)
Mutual labels:  template-engine
jquery-smarty
jQuery Smarty Plugin (jQSmarty) is a port of the Smarty Templating Engine to Javascript/jQuery, offering a familiar client-side templating solution
Stars: ✭ 18 (+0%)
Mutual labels:  template-engine
express-edge
🔤  Use Edge templating engine with Express
Stars: ✭ 45 (+150%)
Mutual labels:  template-engine

Context

Context is package that aims to collect "context" to pass to templates based on a query object.

Best paired with a template engine. And maybe with Hierarchy.


PHP Quality Assurance codecov.io license release


Quick start

Let's assume a couple of classed designed to provide context for the homepage and the singular view, respectively:

use Brain\Context;

class HomepageContext implements Context\ProviderFactory
{
    public function create(\WP_Query $query, LoggerInterface $logger): ?Provider
    {
        return Context\Provider\ArrayMerge::new(fn() => $query->is_front_page())
            ->addProvider(new MyHeroProvider())
            ->addProvider(new Context\Provider\Posts(['posts_per_page' => 5], 'latest_posts'));
    }
}

class SingularContext implements Context\ProviderFactory
{
    public function create(\WP_Query $query, LoggerInterface $logger): ?Provider
    {
        return Context\Provider\ArrayMerge::new(fn() => $query->is_singular())
            ->addProvider(new Context\Provider\ByCallback(fn() => ['post' => $query->post]))
            ->addProvider(new Context\Provider\Comments(['post_id' => $query->post->ID]));
    }
}

Now we can make use of the Context class to generate the context for our templates:

namespace MyTheme;

use Brain\Context;

add_action('template_redirect', function () {
    
    $context = Context\Context::new()
        ->withProviderFactory(new HomepageContext())
        ->withProviderFactory(new SingularContext())
        ->provide();
        
    // pass context to templates here ...
});

Context class emit the action `"brain.context.providers" that can be used to add providers from different places:

namespace MyTheme;

use Brain\Context;

add_action('brain.context.providers', function (Context\Context $context) {
    $context
        ->withProviderFactory(new HomepageContext())
        ->withProviderFactory(new SingularContext());
});

add_action('template_redirect', function () {
    $context = Context\Context::new()->provide();
    // pass context to templates here ...
});

Examples using Hierarchy

Here's an example of using context in combination with Brain Hierarchy to render mustache templates passing them context.

namespace My\Theme;

use Brain\Hierarchy\{Finder, Loader, QueryTemplate};
use Brain\Context;

class MustacheTemplateLoader implements Loader\Loader
{
   private $engine;

   public function __construct(\Mustache_Engine $engine)
   {
      $this->engine = $engine;
   }

   public function load(string $templatePath): string
   {
        // It will be possible to hook 'brain.context.providers' to add context providers
        $data = Context\Context::new()
            ->convertEntitiesToPlainObjects()
            ->forwardGlobals()
            ->provide();

        return $this->engine->render(file_get_contents($templatePath), $data);
   }
}

add_action('template_redirect', function() {
    if (!QueryTemplate::mainQueryTemplateAllowed()) {
        return;
    }

    $queryTemplate = new QueryTemplate(
        new Finder\BySubfolder('templates', 'mustache'),
        new MustacheTemplateLoader(new \Mustache_Engine())
    );

    $content = $queryTemplate->loadTemplate(null, true, $found);
    $found and die($content);
});

Above is all the necessary code to render *.mustache templates from a /templates subfolder in current theme (or parent theme, if any), according to WP template hierarchy, passing to templates context data that can be extended via ad-hoc "view context" classes which will implement Context\ProviderFactory interface.

Providers

Composite providers

The "Quick start" section above uses Context\Provider\ArrayMerge class to "merge" several providers.

Besides that class, there's also a Context\Provider\ArrayMergeRecursive "composite" provider.

Atomic providers

The "composite" providers merge multiple "atomic" providers that can be either custom (anything implementing Context\Provider) or one of the shipped provider classes:

  • ByArray - which provides a given array as-is
  • ByCallback - which provides an array returned by a given callback
  • Comments - which provides an array of comments using given comment query arguments
  • Posts - which provides an array of posts using given post query arguments
  • Subquery - which provides a WP_Query instance using given query arguments
  • Terms - which provides an array of comments using given taxonomy terms query arguments
  • Users - which provides an array of comments using given user query arguments

Custom providers

The Context\Provider interface has a single method:

public function provide(\WP_Query $query, LoggerInterface $logger): ?array;

Which can be implemented to build custom providers. In the case the provider should not be used based on conditions, it can return null.

The given PSR-3 logger interface can be used to log errors and distinguish a provider that returns null due to errors form another that returns null because, for example, not targeting the current query.

Logger

All providers support a PSR-3 logger. Context class implements PSR-3 LoggerAwareInterface, so it is possible to call setLogger when instantiating it.

There's also a "brain.context.logger" action that passes a callback that can be used to set the logger:

add_action('brain.context.logger', function (callable $setter) {
    $setter(new MyPsr3Logger());
});

Requirements

Context requires PHP 7.1+ and Composer to be installed.

Installation

Best served by Composer, available on Packagist with name brain/context.

License

Context is released under MIT.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].