|
1 | 1 | # express-php-view-engine |
2 | | -🐘 Allows you to use PHP as a view engine for Express applications. |
| 2 | + |
| 3 | +[](https://github.com/rooseveltframework/express-php-view-engine/actions?query=workflow%3ACI) [](https://codecov.io/gh/rooseveltframework/express-php-view-engine) [](https://www.npmjs.com/package/express-php-view-engine) |
| 5 | + |
| 6 | +This module allows you to use [PHP](https://php.net) as a templating system for [Express framework](https://expressjs.com) applications. This module was built and is maintained by the [Roosevelt web framework](https://github.com/rooseveltframework/roosevelt) [team](https://github.com/orgs/rooseveltframework/people), but it can be used independently of Roosevelt as well. |
| 7 | + |
| 8 | +## Usage |
| 9 | + |
| 10 | +First declare `express-php-view-engine` as a dependency in your app. |
| 11 | + |
| 12 | +Then set PHP as a view engine in your Express app: |
| 13 | + |
| 14 | +```js |
| 15 | +const express = require('express') |
| 16 | +const app = express() |
| 17 | +const php = require('express-php-view-engine') |
| 18 | + |
| 19 | +// setup php templating engine |
| 20 | +app.set('views', path.join(__dirname, 'templates')) |
| 21 | +app.set('view engine', 'php') |
| 22 | +app.engine('php', php.__express) |
| 23 | + |
| 24 | +// define a route |
| 25 | +app.get('/', (req, res) => { |
| 26 | + res.render('index.php', { |
| 27 | + hello: 'world' |
| 28 | + }) |
| 29 | +}) |
| 30 | +``` |
| 31 | + |
| 32 | +Then, assuming your `templates/index.php` looks like this: |
| 33 | + |
| 34 | +```php |
| 35 | +<p><?=$hello?></p> |
| 36 | +``` |
| 37 | + |
| 38 | +The ouptut will be: |
| 39 | + |
| 40 | +```html |
| 41 | +<p>world</p> |
| 42 | +``` |
| 43 | + |
| 44 | +Note: This module presumes that the system you run this on has PHP installed and that it's in your PATH. |
| 45 | + |
| 46 | +## Configuration |
| 47 | + |
| 48 | +As shown in the above example, `express-php-view-engine` will register values from the Express model as global variables in your PHP script by default. You can disable this behavior if desired two ways: |
| 49 | + |
| 50 | +Disable registering globally: |
| 51 | + |
| 52 | +```js |
| 53 | +const php = require('express-php-view-engine') |
| 54 | +php.disableRegisterGlobalModel() |
| 55 | +// can be reenabled by calling php.enableRegisterGlobalModel() |
| 56 | +``` |
| 57 | + |
| 58 | +Disable registering on a per route basis: |
| 59 | + |
| 60 | +```js |
| 61 | +app.get('/', (req, res) => { |
| 62 | + res.render('index.php', { |
| 63 | + _REGISTER_GLOBAL_MODEL: false, |
| 64 | + hello: 'world' |
| 65 | + }) |
| 66 | +}) |
| 67 | +``` |
0 commit comments