Edge stacks allow you to create content placeholders and push content inside them from other parts of your template. For example, You can create a placeholder for inline JavaScript in the head tag and push script tags inside it from components.
-
Following is the markup of a layout file.
<!DOCTYPE html> <html lang="en"> <head> <!-- Creating a stack for JavaScript --> @stack('js') </head> <body> @!component('button', { message: 'Hello 👋' }) </body> </html>
-
Now, let's create the button component. We will call a frontend JavaScript method
sayMessageevery time someone clicks the button.<button click="sayMessage('{{ message }}')"> Click me to get the message </button>
-
Finally, we must create the
sayMessagefunction. With stacks, you can write JavaScript within the same component file.<button onclick="sayMessage('{{ message }}')"> Click me to get the message </button> @pushTo('js') <script> function sayMessage(message) { alert(message) } </script> @end
The pushTo tag accepts the stack's name in which to push the content. The above example will push the content inside the js stack we defined inside the layout file.
However, the @pushTo tag will push contents as many times as you import the component, which can be a deal breaker in this case.
Therefore, we ship with another @pushOnceTo tag. It pushes the content to a stack only once, regardless of how many times you import the component.
You can install the package from the npm package registry as follows.
npm i edge-stacksAnd use it as a plugin as follows.
import { Edge } from 'edge.js'
import { edgeStacks } from 'edge-stacks'
const edge = new Edge()
edge.use(edgeStacks)AdonisJS users can register the plugin with the View object. Then, to write the setup code, you can create a preload file.
import View from '@ioc:Adonis/Core/View'
import { edgeStacks } from 'edge-stacks'
View.use(edgeStacks)Following is the list of tags registered by this package.
The @stack tag creates a named placeholder where other parts of your template can push content. The tag only accepts a single argument as the name of the stack.
@stack('js')
@stack('css')Calling @stack multiple times with the same name will result in a runtime error.
<!-- ❌ Fails -->
@stack('js')
@stack('js')<!-- ✅ Works -->
@if(foo)
@stack('js')
@elseif (bar)
@stack('js')
@endThe @pushTo tag pushes the contents inside a given named stack. The tag accepts a single argument as the stack name, followed by the content as the tag body.
@pushTo('js')
<script defer>
</script>
@endCalling @pushTo before registering a stack will result in an error.
<!-- ❌ Fails, since the stack is created afterward -->
@pushTo('js')
@end
@stack('js')The @pushOnceTo tag is the same as the @pushTo tag. However, it pushes the contents only once. The @pushOnceTo tag is helpful inside components and partials. So that you can import them multiple times, but the push side-effect happens only once.
@pushOnceTo('js')
<script defer>
</script>
@end