Creating Helper Function

I want to create a helper function [in php] for writing a greeting according to the date and time! Should I create a plugin or is there an opportunity to insert php code elsewhere ?? Thanks!

A plugin is the way to go. You can add your function to an existing plugin such as https://github.com/Sommerregen/grav-plugin-shortcodes/

Hi @timomue,

if you want to do it in PHP then Shortcodes will help you. The only thing you need is to add either a block or inline shortcode via

/ Create block shortcode
$block = new Shortcodes\BlockShortcode('myshortcode', [$shortcode, 'block']);

// Create inline shortcode
$inline = new Shortcodes\InlineShortcode('myshortcode', [$shortcode, 'inline']);

where $shortcode is a callable (see the developer section https://github.com/Sommerregen/grav-plugin-shortcodes/#for-developers ).

Otherwise you may want to use Twig (process.twig) and set up a macro. As long as it has no performance implications, that’s ok.

is there a way to check the date and time in twig ??

http://twig.sensiolabs.org/doc/filters/date.html

Thank you, i am going to create a twig macro… How is a macro structured?

See for example http://twig.sensiolabs.org/doc/advanced.html#filters .

You may also do it in pure Twig with the below snippet (probably needs some improvments though)

{% set hour = "now"|date("g")|number_format %}
{% set m = "now"|date("A") %}

{% if m == "AM" %}
   {% if hour == 12 %}
      <p>Good Evening!</p>
   {% elseif hour < 4 %}
      <p>Good Evening!</p>
   {% elseif hour > 3 %}
      <p>Good Morning!</p>
   {% endif %}
{% else %}
   {% if hour == 12 %}
      <p>Good Afternoon!</p>
   {% elseif hour < 6 %}
      <p>Good Afternoon!</p>
   {% elseif hour > 5 %} 
      <p>Good Evening!</p>
   {% endif %}
{% endif %}
---

yeah, Sommerregen! danke schön !

how to call a macro from within a twig file ?

i’ve got it, thanks!

{% set adjective = random(config.brain.adjectives) %}

Is there a problem?

It doesn’t work for me!

twig’s output is a string full of random numbers !?!?!?

Hi @timomue,

ok it really depends on what type is your variable in config.brain.adjectives. According to the docs If it is an array like

{{ random(['apple', 'orange', 'citrus']) }}

it will for example return “orange”. If you have a string instead {{ random('ABC') }} it will output maybe “C”. I don’t know what you are looking for but try using an array in your config viz.

brain:
   adjectives: ["Bland", "Minty", "Sweet"]
---

does not work properly… :frowning:

Can you provide an example? I guess your variable config.brain.adjectives is empty. Where did you put this into? Check it with {{ dump(config.brain.adjectives) }}. You should see a value in the debug bar.

empty. you’re right. :frowning:

my yaml file “config/brain.yaml”

adjectives:
  - "wunderschön"
  - "angenehm"
  - "wohltuend"
---

maybe grav has a problem finding and rendering my yaml files ?!?!?!?!

I gonna reset my installation of grav.