folded/view

View utilities for your PHP web app.

v0.3.0 2020-10-14 19:01 UTC

This package is auto-updated.

Last update: 2024-11-17 16:26:17 UTC


README

View utilities for your PHP web app.

Packagist License Packagist PHP Version Support Packagist Version Build Status Maintainability TODOs

Summary

About

I created this library to be able to pull it in an existing web app without too much effort setting it up.

Folded is a constellation of packages to help you setting up a web app easily, using ready to plug in packages.

Features

  • Can render Blade views, and pass data to it
  • Can render plain PHP views
  • Can add data to a specific views beforehand (handy if you always need some data in your layouts for example)
  • Eager load the view engine such as it is not booted until you call displayView()

Requirements

  • PHP version >= 7.4.0
  • Composer installed

Installation

1. Install the package

In your root folder directory, run this command:

composer require folded/view

2. Set up the view engine

In the script that is called before displaying your view, add this set up code:

use function Folded\setViewFolderPath;
use function Folded\setViewCacheFolderPath;

setViewFolderPath(__DIR__ . "/views");
setViewCacheFolderPath(__DIR__ . "/cache/views");

The cache is a place where your code is compiled to plain PHP, and stored in the disk, for faster rendering for next requests displaying the view.

Examples

Since this library relies on Laravel's illuminate/view, you can refer to the 7.X documentation if you need any information regarding the Blade syntax and the available Blade directives.

1. Display a view

In this example, we will display a Blade view.

use function Folded\displayView;

displayView("home.index");

With the following content inside views/home/index.blade.php:

<h1>Hello world</h1>

2. Pass data to your view

In this example, we will pass a string to the view we display.

use function Folded\displayView;

displayView("home.index", [
  "name" => "John",
]);

With the following content inside the view:

<h1>Hello world</h1>

<p>Welcome to my website, {{ $name }}.</p>

3. Display a plain PHP view

In this example, we will display a plain PHP file.

use function Folded\displayView;

displayView("about-us.index");

The plain PHP view is located at views/about-us/index.php (notice there is no "blade" extension now), with the following content:

<h1>About us</h1>

4. Always pass certain data to a view

In this example, we will pass a company name to a layout view, to be able to not add it to every view that extends the layout.

use function Folded\addDataToView;

addDataToView("layouts.base", [
  "companyName" => "Folded",
]);

5. Get the rendered view

In this example, we will get the rendered view in a variable (useful to send emails for example).

use function Folded\getRenderedView;

$content = getRenderedView("emails.account-created");

Version support