Giter Club home page Giter Club logo

twig-wordpress's Introduction

Build Status codecov Scrutinizer Code Quality

Twig for WordPress

Twig for WordPress allow you to use the famous Twig template engine https://twig.symfony.com/ but extend it to be able to use the functions provided by WordPress such as esc_html, esc_html__, wp_kses etc...

This package register the escape function as filters and functions because translator functions need to be pass a textdomain.

Modules

The package provide filters, functions and other stuffs into twig by define modules.

Modules are class instances that implements an interface TwigWp\Module\Injectable used by the Provider TwigWp\Module\Provider that allow us to retrieve all modules to be set into twig instance.

There is a filter twigwp.modules within the Provider::modules method that allow third party softwares to hook into the modules list so, they'll be able to add other filters, functions, tags or whatever they want to use to extend the twig instance (read about how to extend twig here https://twig.symfony.com/doc/2.x/advanced.html).

Escapers

Twig for WordPress define as filters and functions the followings:

  • esc_js
  • esc_sql
  • esc_textarea
  • esc_url
  • esc_url_raw
  • esc_attr
  • esc_html

Kses

The kses are defined only as functions.

  • wp_kses
  • wp_kses_post
  • wp_kses_allowed_html

Sanitizers

The sanitizers are defined only as functions.

  • sanitize_html_class
  • sanitize_text_field
  • sanitize_title
  • sanitize_key

L10n

Localization functions, including the escaped ones. Localizations functions that start with esc_ (escape) are also registered as filters.

  • __
  • _e
  • _n
  • _x
  • _ex
  • _nx
  • esc_attr__
  • esc_attr_e
  • esc_attr_x
  • esc_html__
  • esc_html_e
  • esc_html_x

Template Functions

This module include all of the functions that echo html markup even if them are not WordPress template functions.

This because most of the WordPress functions usually get some configuration by array and output html markup. Having to put in a object property the entire markup isn't usefull since you want to have your markup into your views, these functions will help you to pass the configuration and call the output function directly, avoiding to permit to parse html markup that may result in a unescaped html.

  • wp_nav_menu
  • get_adjacent_post_link

Provider

The modules are retrieved by a Provider.

Within the provider the modules can be filtered twigwp.modules.

So if you want to add a new module you can hook into this filter and return a new instance of TwigWp\Module\Injectable.

A Module is used to extend the twig instance, the method injectInto get a \Twig\Environment instance to use for example to add a new function, a new filter or a new tag etc...

For example:

class MyModule implements TwigWp\Module\Injectable {

	public function injectInto(\Twig\Environment $twig): \Twig\Environment {
		// Do your stuffs here.

		return $twig;
	}

}

$provider = new Provider(new \Twig\Environmnet());

add_filter('twigwp.modules', function($modules)
{
	$modules['module_name'] = new MyModule();

	return $modules;
});

$modules = $provider->modules();

This is just an example because you'll never need to create an instance of the Module Provider. Everything is handled by the Factory class.

You just need to add your filter and everything is ok.

Factory

The package provide a Factory class that help you on creating a new instance of the \Twig\Environment class.

If you want to create a new Twig instance you can simply create a factory instance by passing a \Twig\Loader\LoaderInterface object and the twig options if you want to customize the environment.

Then call the create method and you've done.

$twigFactory = new \TwigWp\Factory(
	new \Twig\Loader\FilesystemLoader(),
	[
        'debug' => false,
        'charset' => 'UTF-8',
        'base_template_class' => 'Twig_Template',
        'strict_variables' => false,
        'autoescape' => 'html',
        'cache' => false,
        'auto_reload' => null,
        'optimizations' => -1,
	]
);

$twig = $twigFactory->create();

Pretty easy, right?

License

This programm is free software and is licensed using GPL2.

For more info about the license see https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html

Requirements

PHP >= 7.0

Bugs Reporting

To report bugs please refer to https://github.com/widoz/twig-wordpress/issues

Support

For support just open a new issue https://github.com/widoz/twig-wordpress/issues and apply the label help wanted.

twig-wordpress's People

Contributors

scrutinizer-auto-fixer avatar widoz avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

twig-wordpress's Issues

Add `sanitize_html_class` as filter not only as function

sanitize_html_class is often used as a function call within the class property so, make sense to have it also as a filter not only as a function.

Since there is not way currently to define a function + a filter once, could be ok to include it together with the escapers.

Introduce get_comment_pages_count() and paginate_comments_links()

Regarding get_comment_pages_count may be a wrapper has_comment_pages so we don't need to make the developer check agains get_comment_pages_count() > 1 everytime.

For paginate_comments_links may be a wrapper would be better so we don't need to add custom configuration.

Or at least, let's just pass the labels such as:

paginate_comments_links(
    esc_html__('Page', 'textdomain'), 
    esc_html__('Previous Comments', 'textdomain'),
    esc_html__('Next Comments', 'textdomain')
)

Introduce wp_link_pages() and make html classes bem like

Consider part of the deleted implementation from wordpress-model

<?php # -*- coding: utf-8 -*-

/*
 * This file is part of the WordPress Theme Model package.
 *
 * (c) Guido Scialfa <[email protected]>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace WordPressModel\Model;

use Widoz\Bem\Factory;
use Widoz\Bem\Valuable;

/**
 * Paginate Post Model
 */
final class PostPaginate implements FullFilledModel
{
    public const FILTER_DATA = 'wordpressmodel.post_paginate';
    public const FILTER_PAGINATE_LIST = 'wp_link_pages_link';

    /**
     * @inheritdoc
     */
    public function data(): array
    {
        $bem = Factory::createServiceForStandard('pagination');

        if (!$this->isMultipage()) {
            /**
             * Post Paginate Filter
             *
             * @param array $data The post paginate data
             */
            return apply_filters(self::FILTER_DATA, []);
        }

        add_filter(
            self::FILTER_PAGINATE_LIST,
            [$this, 'makePaginationMarkupClassesBemLike'],
            0
        );

        /**
         * Post Paginate Filter
         *
         * @param array $data The post paginate data
         */
        $data = apply_filters(self::FILTER_DATA, [
            'container' => [
                'attributes' => [
                    'class' => $bem,
                ],
            ],
            'markup' => \wp_link_pages([
                'echo' => 0,
                'before' => $this->before($bem->value()),
                'after' => $this->after(),
                'link_before' => $this->linkBefore(),
            ]),
        ]);

        remove_filter(
            self::FILTER_PAGINATE_LIST,
            [$this, 'makePaginationMarkupClassesBemLike'],
            0
        );

        return $data;
    }

    /**
     * @return mixed
     */
    private function isMultipage(): bool
    {
        global $multipage;

        return $multipage;
    }

    /**
     * Make Pagination Attribute Class Bem Like
     * Change the class attribute value with ones that provide bem like string.
     *
     * @param string $link
     *
     * @return string The filtered link
     */
    public function makePaginationMarkupClassesBemLike(string $link): string
    {
        $bem = Factory::createServiceForStandard('pagination');

        $link = '<li class="' . \sanitize_html_class($bem->forElement('item')) . '">' . $link . '</li>';

        return $link;
    }

    /**
     * @param Valuable $bem
     * @return string
     */
    private function before(Valuable $bem): string
    {
        return '<ul class="' . \sanitize_html_class($bem) . '">';
    }

    /**
     * @return string
     */
    private function after(): string
    {
        return '</ul>';
    }

    /**
     * @return string
     */
    private function linkBefore(): string
    {
        return \sprintf(
            '<span class="screen-reader-text">%s</span>',
            \esc_html_x('Page', 'pagination', 'wordpress-model')
        );
    }
}

Introduce paginate_links()

Similar to paginate_comments_links() (see #13) we could allow to pass the labels.

A wrapper would be great but not sure how to make the classes bem like.
See f10a5c8fab0b32e26cec245a42457aec8b372cf0 in wordpress-model for more informations.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.