1

I have added a number field with prefix, suffix and currency symbol: enter image description here

How can I add a variable to a template which shows the number with prefix, suffix and currency? I tried the following which didn't work: {{ entry.rentalPrice|money }}

I couldn't find the information in the documentation: https://craftcms.com/docs/5.x/reference/field-types/number.html

1 Answer 1

2

Fetching the field and outputting the following should work.

{% set field = craft.app.fields.getFieldByHandle('my-field-handle') %}
{{ field.prefix }}
{{ entry.rentalPrice }}
{{ field.suffix }}
{{ field.previewCurrency }}

Class reference: https://docs.craftcms.com/api/v5/craft-fields-number.html#public-properties

5
  • Thank you. Unfortunately, for me it doesn't work. I am using CraftCMS 5.x. I get an error: Twig Runtime Error – Twig\Error\RuntimeError / Impossible to access an attribute ("prefix") on a integer variable ("175"). / Impossible to access an attribute ("suffix") on a integer variable ("175"). / Impossible to access an attribute ("previewCurrency") on a integer variable ("175"). Even better would be to have just one variable that will show the field value including prefix, suffix and currency.
    – flip
    Commented Apr 8 at 7:38
  • I also tried {{ entry.rentalPrice.currency ?? null }} which neither produces an error nor shows any data. I have set a value for prefix, suffix and currency so it shouldn't be empty.
    – flip
    Commented Apr 8 at 8:55
  • Oh right, I forgot that the normalised value is returned. I updated my answer to fetch the field itself.
    – Ben Croker
    Commented Apr 8 at 18:47
  • Thank you! It works but it is a lot of code for one field. According to this documentation it should be craft.app.fields.getFieldByHandle instead of craft.app.fields.fieldByHandle: craftcms.com/docs/5.x/reference/twig/global-variables.html
    – flip
    Commented Apr 9 at 11:32
  • Both work, but I updated my answer to match the docs. It’s really just one line of code to get the field. The rest is to output it in whatever format you want.
    – Ben Croker
    Commented Apr 10 at 0:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.