| 1 |
<?php |
| 2 |
|
| 3 |
namespace WGMSRM\Traits; |
| 4 |
|
| 5 |
if (!defined('ABSPATH')) { |
| 6 |
exit; |
| 7 |
} |
| 8 |
|
| 9 |
trait TemplateRenderer |
| 10 |
{ |
| 11 |
/** |
| 12 |
* Render a template file with data. |
| 13 |
* |
| 14 |
* @param string $template_name Relative path to template inside 'templates' dir. |
| 15 |
* @param array $data Associative array of data to extract. |
| 16 |
* @param bool $echo Whether to echo or return the content. |
| 17 |
* @return string|void |
| 18 |
*/ |
| 19 |
public function render($template_name, $data = [], $echo = false) |
| 20 |
{ |
| 21 |
$template_path = WGM_PLUGIN_PATH . 'templates/' . $template_name . '.php'; |
| 22 |
|
| 23 |
if (!file_exists($template_path)) { |
| 24 |
return ''; |
| 25 |
} |
| 26 |
|
| 27 |
if (!empty($data)) { |
| 28 |
extract($data); |
| 29 |
} |
| 30 |
|
| 31 |
ob_start(); |
| 32 |
include $template_path; |
| 33 |
$output = ob_get_clean(); |
| 34 |
|
| 35 |
if ($echo) { |
| 36 |
echo $output; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped |
| 37 |
} else { |
| 38 |
return $output; |
| 39 |
} |
| 40 |
} |
| 41 |
} |
| 42 |
|