1

I have a template

{{#if currentUser}}
    <input id="datetimepicker" type="text" >
{{/if}}

I want do add

$('#datetimepicker').datetimepicker();

But in methods of template:

  • onCreated
  • onRendered

content of {{#if currentUser}} is not accessible because collection with user is loaded after template. I can use setTimeout, but this is non stable solution. I can to type in template

{{#if currentUser}}
    <input id="datetimepicker" type="text" >
    <script>
        $('#datetimepicker').datetimepicker();
    </script>
{{/if}}

but this is not elegant.

How to catch rendering of content in block {{if currentUser}} in correct way? Or maybe should I not use this syntax generally and there is other manner of checking is user is loaded. If yes, link to proper tutorial please.

pneumatics
  • 2,836
  • 1
  • 27
  • 27
Daniel
  • 7,684
  • 7
  • 52
  • 76

2 Answers2

1

The way to do this is to make the content of the if another template, and then use the onRendered or onCreated methods of that template.

{{#if currentUser}}
    {{> datePicker}}
{{/if}}
...

<template name="datePicker">
  <input id="datetimepicker" type="text" >
</template>

JS:

Template.datePicker.onCreated(() => {
  // something
});
Christian Fritz
  • 20,641
  • 3
  • 42
  • 71
1

@Christian Fritz's answer works well.

In case you don't want to create a new template because of some other issues, you can also try this in the onRendered callback:

Tracker.autorun(function() {
  if ($('#datetimepicker')[0]) {
    $('#datetimepicker').datetimepicker();
  }
});
Christian Fritz
  • 20,641
  • 3
  • 42
  • 71
Sasikanth
  • 3,045
  • 1
  • 22
  • 45