Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] Call function dynamically ? #559

Open
raskyer opened this issue Jul 19, 2024 · 1 comment
Open

[Question] Call function dynamically ? #559

raskyer opened this issue Jul 19, 2024 · 1 comment
Labels

Comments

@raskyer
Copy link

raskyer commented Jul 19, 2024

Hello,

I'm trying to migrate nunjuck templates in scriban templates and I am wondering if in scriban we can call function based on dynamic name.

For example in nunjuck we have this :

{% import 'modules_html.njk' as modules_html %}

{{ modules_html[element.type](element) }}

in modules_html.njk we have :

{% macro image(element) %}
  ... html
{% endmacro %}

{% macro video(element) %}
  ... html
{% endmacro %}

For now, in scriban I have this :

{{ modules_html = include 'modules_html.scriban' }}

{{ modules_html[element.type](element) }}

And in modules_html.scriban :

{{ func image(element) }}
  ... html
{{ end }}

{{ func video(element) }}
  ... html
{{ end }}

But it's not really working. So is there an easy workaround for this type of thing ?

  • Import template functions and used them with the predefined name (in this case modules_html)
  • Call template function dynamically based on a property of global scope (in this case element.type)
@xoofx
Copy link
Member

xoofx commented Jul 30, 2024

For now, in scriban I have this :

{{ modules_html = include 'modules_html.scriban' }}

{{ modules_html[element.type](element) }}

include is a function that returns a string of the include but all variable declared in it is going to be visible in the currently bound this context. In that case your image/video functions are directly accessible via image(x,y,z) or this["image"](x,y,z)

If you wanted to capture to an object all the declarations of modules_html.scriban you would have to use with statement:

{{
modules_html = {}
with modules_html
    $discard = include 'modules_html.scriban'
end
}}

@xoofx xoofx added the question label Jul 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants