1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace MySociety\TheyWorkForYou\Renderer; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Markdown Renderer |
7
|
|
|
* |
8
|
|
|
* Use for converting markdown into help pages. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
|
12
|
|
|
|
13
|
|
|
class Markdown { |
14
|
|
|
public function markdown_document(string $this_page, bool $show_menu = true, array $extra_vars = []) { |
15
|
|
|
// This function takes a markdown file and converts it to HTML |
16
|
|
|
|
17
|
|
|
$markdown_file = '../../../markdown/' . $this_page . '.md'; |
18
|
|
|
$Parsedown = new \Parsedown(); |
19
|
|
|
|
20
|
|
|
$text = file_get_contents($markdown_file); |
21
|
|
|
$html = $Parsedown->text($text); |
22
|
|
|
|
23
|
|
|
# title is the first h1 |
24
|
|
|
preg_match('/<h1>([^<]+)<\/h1>/i', $html, $matches); |
25
|
|
|
|
26
|
|
|
$title = $extra_vars['_page_title'] ?? $matches[1]; |
27
|
|
|
|
28
|
|
|
$html = preg_replace_callback('/<h([1-3])>([^<]+)<\/h[1-3]>/i', function ($matches) { |
29
|
|
|
$level = $matches[1]; |
30
|
|
|
$htitle = $matches[2]; |
31
|
|
|
$slug = slugify($htitle); |
32
|
|
|
if ($level == 1) { |
33
|
|
|
$title_class = "js-toc-title"; |
34
|
|
|
} else { |
35
|
|
|
$title_class = "js-toc-item"; |
36
|
|
|
} |
37
|
|
|
return "<h$level id=\"$slug\" class=\"$title_class\">$htitle</h$level>"; |
38
|
|
|
}, $html); |
39
|
|
|
|
40
|
|
|
// Create new panel when horizontal line used |
41
|
|
|
$html = preg_replace('/<hr \/>/i', '</div><div class="panel">', $html); |
42
|
|
|
|
43
|
|
|
foreach ($extra_vars as $key => $value) { |
44
|
|
|
$html = str_replace('{{ ' . $key . ' }}', $value, $html); |
45
|
|
|
}; |
46
|
|
|
|
47
|
|
|
$context = [ |
48
|
|
|
'html' => $html, |
49
|
|
|
'this_page' => $this_page, |
50
|
|
|
'page_title' => $title, |
51
|
|
|
'show_menu' => $show_menu, |
52
|
|
|
]; |
53
|
|
|
|
54
|
|
|
// Add extra variables to the context |
55
|
|
|
foreach ($extra_vars as $key => $value) { |
56
|
|
|
$context[$key] = $value; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
\MySociety\TheyWorkForYou\Renderer::output('static/markdown_template', $context); |
60
|
|
|
|
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public static function render_php($template_file, array $context = []) { |
64
|
|
|
$path = INCLUDESPATH . 'easyparliament/templates/html/' . $template_file . '.php'; |
|
|
|
|
65
|
|
|
extract($context, EXTR_SKIP); |
66
|
|
|
ob_start(); |
67
|
|
|
include($path); |
68
|
|
|
return ob_get_clean(); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|