Javascript functions in templates


#1

Hi.

I’m trying to some javascript in my template, but it always throws an error. What kind of Javascript methods are valid in templates?


#2

I’m trying to show a percentage with a toFixed(2) to only show two decimals. this works:
{{ interest.meta.customers_count.toFixed(2) }}
while this does not work:
{{ interest.meta.customers_count/stats.usersCount.toFixed(2) }}


#3

Directly in Edge templates are valid only Javascript Expression, like ternary operator etc. (I’m not sure, maybe someone more experienced could confirm or deflate this)

So in case you wanna use custom function you need to register it as globals - http://adonisjs.com/docs/4.0/ignitor#_hooks


#4

I guess the problem with slash, so it can’t be evaluated.


#5

with the slash it gives me the number with all the decimals, and ignores the toFixed(). (does not return an error)


#6

What is the error you are getting?


#7

The error is that when I write

{{ (interest._ _ meta _ _.customers_count / stats.usersCount).toFixed(2) }}

it ignores toFIxed and show the whole number with all the decimals.
if I try to multiply with *100 after stats.usersCount it says unexpected or invalid token so the problem is probably the *. I guess its not possible to do it like this?


#8

By the error you mean it’s not working as expected or it throws some error.

If it throws some error, then please share the exact error


#9

It gives me a 500 SyntaxError Invalid or unexpected token when I try to include *100.


#10

Can u share the exact code and a screenshot of the error?


#11
 @each(interest in interests)
          <div class="d-flex mb-1 col-sm-4">
            <div class="label col-sm-8">
              {{interest.name}}
            </div>
            <p class="text-dark small col-sm-4">
              {{ ((interest.__meta__.customers_count / stats.usersCount) * 100).toFixed(2) }}
            </p>
          </div>
        @endeach


#12

Yup seems like at the AST level, the Punctuator ( messes up. For now I can suggest creating a function and letting that function does the calculation.


#13

Yep. I’ve found a work-around for now, but it would be great to be able to do stuff like this in the template in the future.