Skip to content

Commit

Permalink
Improve view function
Browse files Browse the repository at this point in the history
  • Loading branch information
xepozz committed Jul 24, 2023
1 parent ad9601b commit ac2f6a3
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,17 @@ route('user/view', ['id' => 1]); // => '/user/1'
route('site/index', [], ['page' => 2]); // => '/index?page=2'
```

### `view(string $view, array $params = [], ?object $controller = null): \Yiisoft\DataResponse\DataResponse`
### `view(string $view, array $params = [], null|string|object $controller = null): \Yiisoft\DataResponse\DataResponse`

- `$view` is a view name
- `$params` is a view params
- `$controller` is a controller instance. Used to bind views to the specific directory called by the controller name.
- `$controller` is a controller instance or a path to views directory. Used to bind views to the specific directory.

```php
view('site/index'); // => A response object with content of file '/views/site/index.php'
view('site/index', ['page' => 2]); // => A response object with content of file '/views/site/index.php' and params ['page' => 2]
view('index', ['page' => 2], new MyController()); // => A response object with content of file '/views/my/index.php' and params ['page' => 2]
view('index', ['user' => $user], 'module/user'); // => A response object with content of file '/views/module/user/index.php' and params ['user' => $user]

class SiteController
{
Expand Down
6 changes: 4 additions & 2 deletions src/view.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,16 @@
function view(
string $view,
array $parameters = [],
?object $controller = null
null|string|object $controller = null
): DataResponse {
/**
* @var ViewRenderer $renderer
*/
$renderer = container(ViewRenderer::class);
if ($controller !== null) {
if (is_object($controller)) {
$renderer = $renderer->withController($controller);
} elseif(is_string($controller)) {
$renderer = $renderer->withControllerName($controller);
}
return $renderer->render($view, $parameters);
}

0 comments on commit ac2f6a3

Please sign in to comment.