No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

highlight.php 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace Grav\Plugin;
  3. use \Grav\Common\Plugin;
  4. use \Grav\Common\Grav;
  5. use \Grav\Common\Page\Page;
  6. class HighlightPlugin extends Plugin
  7. {
  8. /**
  9. * @return array
  10. */
  11. public static function getSubscribedEvents()
  12. {
  13. return [
  14. 'onPageInitialized' => ['onPageInitialized', 0]
  15. ];
  16. }
  17. /**
  18. * Initialize configuration
  19. */
  20. public function onPageInitialized()
  21. {
  22. if ($this->isAdmin()) {
  23. $this->active = false;
  24. return;
  25. }
  26. $defaults = (array) $this->config->get('plugins.highlight');
  27. /** @var Page $page */
  28. $page = $this->grav['page'];
  29. if (isset($page->header()->highlight)) {
  30. $this->config->set('plugins.highlight', array_merge($defaults, $page->header()->highlight));
  31. }
  32. if ($this->config->get('plugins.highlight.enabled')) {
  33. $this->enable([
  34. 'onTwigSiteVariables' => ['onTwigSiteVariables', 0]
  35. ]);
  36. }
  37. }
  38. /**
  39. * if enabled on this page, load the JS + CSS theme.
  40. */
  41. public function onTwigSiteVariables()
  42. {
  43. $init = "$(document).ready(function() {\n";
  44. $init .= "$('pre code').each(function(i, block) {\n";
  45. $init .= "hljs.highlightBlock(block);\n";
  46. if ($this->config->get('plugins.highlight.lines')) {
  47. $init .= "hljs.initLineNumbersOnLoad();\n";
  48. }
  49. $init .= "});\n";
  50. $init .= "});\n";
  51. $theme = $this->config->get('plugins.highlight.theme') ?: 'default';
  52. $this->grav['assets']->addCss('plugin://highlight/css/'.$theme.'.css');
  53. $this->grav['assets']->addJs('plugin://highlight/js/highlight.pack.js');
  54. if ($this->config->get('plugins.highlight.lines')) {
  55. $this->grav['assets']->addJs('plugin://highlight/js/highlightjs-line-numbers.min.js');
  56. }
  57. $this->grav['assets']->addInlineJs($init);
  58. }
  59. }