XF 2.3 Phrases and Javascript

Taylor J

Well-known member
I'm currently having some issues with phrases in Javascript where it's just rendering out the name of the phrase
1724033172566.webp

My javascript is below:
JavaScript:
((window, document) => {
  "use strict";

  // XF.extendObject(XF.phrases,
  //     {
  //         taylorj_blogs_blog_post_read_time: "{{ phrase('taylorj_blogs_blog_post_read_time')|escape('js') }}",
  //     });

  XF.TaylorJBlogs = XF.Element.newHandler({
    init() {
      const words = document.getElementsByClassName("bbWrapper")[0];
      const readTimeDiv = document.getElementsByClassName(
        "taylorj-blogs-read-time"
      )[0];
      const wordCount = words.innerText.trim().split(/\s+/).length;
      const readTime = Math.ceil(wordCount / 225);
      console.log(readTime);

      const test = XF.phrase("taylorj_blogs_blog_post_read_time", {readTime: readTime});
      console.log(test);

      readTimeDiv.innerText = XF.phrase("taylorj_blogs_blog_post_read_time", {
        readTime: `${readTime}`,
      });
    },
  });

    XF.Element.register('taylorj-blogs', 'XF.TaylorJBlogs')
})(window, document);

The console log is also just spitting out the name of the phrase as well.

I've also tried extending the phrases seen by the commented out lines in my JS above.

Phrase is already created
1724033172569.webp

Is there something I'm doing completely wrong here?
 

Attachments

  • 1724033034783.webp
    1724033034783.webp
    2.7 KB · Views: 2
I am probably just going to accomplish this (and probably everything else that needs to use a phrase in Javascript) with PHP.

It's even doing it for other phrases
1724074809638.webp
 
You need to listene to DOMContentLoaded event.

What i'm doning in my addons usually i create a template or macro just for js phrases and config then i add my phrases like this:

HTML:
<xf:macro id="addon_js_macros">
    <script>
        window.addEventListener('DOMContentLoaded', () => {
            XF.extendObject(XF.phrases, {
                some_phrase: "{{ phrase('some_phrase')|escape('js') }}",
            })
            XF.extendObject(XF.config, {
                some_config: "{{ $xf.options.some_option }}",
            })
        })
    </script>
</xf:macro>

And i inject this macro in helper_js_global template below <!--XF:JS-->/s

Then in js file i use it this way:

JavaScript:
// use phrase
XF.phrase('some_phrase', {some_param: 'some_value'})
// use config value
XF.config.some_config
 
Back
Top Bottom