Skip to content

How to make a custom helper for template? [V5] #3453

Answered by Julien-R44
pk4all asked this question in Help
Discussion options

You must be logged in to vote

Hello, looks at this : https://docs.adonisjs.com/guides/views/data-flow#globals

You have to define your helpers in an preloaded file so :

node ace make:prldfile ViewHelpers

And select "during HTTP server"

Your .adonisrc.json should contains this now :

{
  "preloads": [
    "./start/routes",
    "./start/kernel",
    {
      "file": "./start/ViewHelpers",
      "environment": [
        "web"
      ]
    }
  ],

Now you can define your helper in start/ViewHelpers :

import View from '@ioc:Adonis/Core/View'

View.global('nl2br', function (text) {
  return text.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br />$2')
})

In your template :

<p> {{{ nl2br(post.description) }}} </p>

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@pk4all
Comment options

Answer selected by pk4all
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet
2 participants