Coder Social home page Coder Social logo

slime-render's Introduction

SLIME Render

PHP abstraction functions to help more easily render views for Slim Framework (v4) with plain text, HTML, JSON, and Handlebars (using LightnCandy)

These functions aim to provide a simplified and standardized interface for rendering various types of data-driven responses as PSR-7 objects for use with Slim.

Included with the Slime boilerplate for Slim applications.

Installation

Easy install with composer:

composer require jyoungblood/slime-render
use Slime\render;
require __DIR__ . '/vendor/autoload.php';

Requirements

Usage

render::html($request, $response, $string, $status = 200)

Renders a string as HTML. Returns a standard Slim (PSR-7) response object with optional HTTP status code (200 by default).

$app->get('/', function ($req, $res, $args) {

  return render::html($req, $res, '<h2>Hey whats up</h2>');

});

Additionally, a path to an HTML file can be specified to load and render instead of a string:

$app->get('/', function ($req, $res, $args) {

  return render::html($req, $res, '/hey/whats-up.html');

});

render::text($request, $response, $string, $status = 200)

Renders a string as plain text. Returns a standard Slim (PSR-7) response object with optional HTTP status code (200 by default).

$app->get('/', function ($req, $res, $args) {

  return render::text($req, $res, 'Hey whats up');

});

render::hbs($request, $response, $parameters, $status = 200)

Renders a specific Handlebars template with an array of data, including any partials and global locals variables array. Returns a standard Slim (PSR-7) response object with optional HTTP status code (200 by default).

$app->get('/', function ($req, $res, $args) {

  return render::hbs($req, $res, [
    'template' => 'index',
    'layout' => '_layouts/base', // optional "wrapper" layout template
    'title' => 'Page title', // for HTML <title> tag
    'data' => [
      'name' => 'Ringo',
      'friends' => [
        'Paul', 'George', 'John'
      ]
    ],
  ], 200); // optional status code, 200 by default

});

The parser function expects templates to be in a templates directory with html file extension. This can be customized by defining these variables in a global settings array:

$GLOBALS['settings']['templates']['path'] = 'pages';
$GLOBALS['settings']['templates']['extension'] = 'hbs';

Additionally, an array of locals can be added to make variables available across all templates:

$GLOBALS['locals'] = [
  'year' => date('Y'),
  'site_title' => 'Web Site Title',
  'site_code' => 'WST',
  'site_domain' => 'example.com',
];
Welcome to {{locals.site_title}}, the year is {{locals.year}}!

Parameters from PHP $_GET and $_POST variables are automatically made available to templates rendered with this function, using the variables {{GET}} and {{POST}}:

<!-- assuming a url like /hello/?name=Delilah&location=New%20York%20City -->
Hey there, {{GET.name}}, what's it like in {{GET.location}}?

Check out the Handlebars Cookbook to see everything you can do with LightnCandy and Handlebars.

Additionally, we've included a couple of helper functions.

The date helper applies the PHP date() function to a given variable or string (or now keyword for the current time)

Date from unix timestamp: {{date unix_ts_var "d/m/Y"}}
Current date: {{date "now" "d/m/Y"}} <!-- use the "now" keyword instead of a variable to use the current time -->
Date from non-unix timestamp: {{date non_unix_ts_var "d/m/Y" "convert"}} <!-- add the "convert" parameter to convert the variable to unix time using strtotime() -->

The #is block helper allows for basic conditional logic:

Is it 1981? {{#is locals.year "==" "1981"}} Yes! {{else}} No! {{/is}}

Custom helpers are easy to create. Take a look at how these helpers are defined in initialize_handlebars_helpers(). The Handlebars cookbook also has a reference for creating custom helpers and custom block helpers.

render::handlebars($parameters)

Renders a specicific Handlebars template with data array the same as render::hbs(), but returns raw html instead of a PSR-7 response.

$app->get('/', function ($req, $res, $args) {

  echo render::handlebars([
    'template' => 'email/test',
    'data' => [
      'link' => 'https://jy.hxgf.io',
    ]
  ]);

  return $res;
});

render::redirect($request, $response, $string, $status = 302)

Renders a redirect as standard Slim (PSR-7) response object with optional HTTP status code.

  return render::redirect($req, $res, 'https://google.com/');

render::json($request, $response, $data, $status = 200)

Renders an array or data as standard Slim (PSR-7) response object with application/json content type and optional HTTP status code.

$app->get('/json/', function ($req, $res, $args) {

  $data = [
    'name' => 'Ringo',
    'friends' => [
      'Paul', 'George', 'John'
    ]
  ];

  return render::json($req, $res, $data);

});

render::lightncandy_html($parameters)($data)

Prepares and compiles a specific Handlebars template with an array of data, including any partials and global locals variables array.
This is automatically called by render::hbs() but can be used as a standalone function if desired.

$args = [
  'template' => 'index',
  'layout' => '_layouts/base',
  'title' => 'Page title',
];

$data = [
  'name' => 'Ringo',
  'friends' => [
    'Paul', 'George', 'John'
  ]
];

echo render::lightncandy_html($args)($data);

render::initialize_handlebars_helpers()

For internal use by lightncandy_html(). Defines a couple custom Handlebars helper functions to be used by the LightnCandy compiler.

slime-render's People

Contributors

jyoungblood avatar

Stargazers

evan70 avatar

Watchers

 avatar

slime-render's Issues

Consider alternate term for "locals"

We have a group of global (site-wide) variables that are available by default for every template that is rendered. They need to be grouped in their own array/namespace and "locals" seemed like a good name at the time.

I feel like there's a more fitting term we could use, though, that more accurately conveys the nature of these variables and how they relate to the rest of the application.

Add support for other templating languages

HBS is great (and really the only kind of templates I care about), but I'm wondering if it would be helpful to provide these same kinds of abstractions for other template languages?

I'm specifically thinking:

There are more (HAML, Pug, Nunjucks, Smarty, Golang, etc) but I don't want to get carried away.

If so, we'd probably need to add some instructions for installing the supporting rendering packages.

What do you think? Cool idea? Too much? Sound off in the comments!

Add example of how to build & initialize custom HBS helpers

Add a couple simple examples to the readme, basically a copy of what's in the initialize_handlebars_helpers() function:

$GLOBALS['hbars_helpers']['date'] = function ($arg1, $arg2, $arg3 = false) {
  if (isset($arg1) && $arg1 != ''){
    if ($arg1 == "now"){
      return date($arg2);
    }else{
      if ($arg3 == "convert"){
        return date($arg2, strtotime($arg1));
      }else{
        return date($arg2, $arg1);
      }
    }
  }else{
    return false;
  }
};

Except we'd want a really simple function that could be copy/pasted.

Want to have an example of both a regular and block helper.

New render::error() Function (with default 'error' templates)

Basically an abstraction for rendering a template with render::hbs() or render::html(). It would use a general error template to show messages and error codes determined by the controller, and of course send the HTTP status code with the response.

Yes the design is stolen from the default Next.js error page.

We started working with a similar concept in dw 0.6. See the base route/controller setup (the $errorMiddleware->setErrorHandler part) and general error template for more details.

Docs - Add another example of one-off rendering with render::handlebars()

Something along the lines of "you can use shared layouts with templates in other contexts...like sending emails, for example"

My particular use case involving email_send from x-utilities (I use this pattern all the time)

  \VPHP\x::email_send([
    'to' => '[email protected]',
    'from' => '"'.$_ENV['SITE_TITLE'].'" <notifications@'.$_ENV['MAILGUN_DOMAIN'].'>',
    'subject' => 'This email uses a template!',
    'html' => true,
    'message' => render::handlebars([
      'layout' => '_layouts/email',
      'template' => 'email/new-donation',
      'data' => [
        'donation' => $donation,
        'donor' => $donor
      ]
    ])
  ]);

More HBS Helpers!

Probably best to do this as a separate package, but at some point I'd love to see more HBS helpers.

For inspiration: Assembly has a HUGE library of custom helpers for the JS version of handlebars, and BigCommerce's theme engine (Stencil) also has a good collection of helpers.

I also wrote a handful of helpers for js back in the day, idk if any of them would still be useful: https://github.com/hxgf/lexxi-handlebars/blob/master/index.js

It's easy enough to build custom helpers now, so we'd just need to make PHP versions of these.

Questions:

  • Are there any changes we'd want to make in how we're initializing the helpers?
  • Instead of a separate package, would it be better to just have these available as copypastas in some docs somewhere?

Add description and example of how base (layout) parsing works

It's similar to how many frameworks (Django, Express, Laravel, etc) handle layouts so it's nothing super unique...I just think it's worth describing in the readme.

Essentially: "define a layout template, any new html generated by the controller will be rendered into the {{outlet}} tag," show a simple example, and link to the slime boilerplate base layout template.

Might also want to note which "global" variables will be rendered on the base template ({{title}}, {{locals}}, {{GET}}, etc)

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.