Operator logiczny w kierownicy.js {{#if}} warunkowe

Czy w kierownicy JS istnieje sposób na włączenie operatorów logicznych do Standardowej kierownicy.operator warunkowy js? Coś takiego:

{{#if section1 || section2}}
.. content
{{/if}}
Wiem, że mógłbym napisać własnego pomocnika, ale najpierw chciałbym się upewnić, że nie wymyślam koła na nowo.
Author: Mike Robinson, 2012-01-13

26 answers

Jest to możliwe przez "oszukanie" z pomocnikiem bloku. Prawdopodobnie jest to sprzeczne z ideologią ludzi, którzy opracowali Kierownice.

Handlebars.registerHelper('ifCond', function(v1, v2, options) {
  if(v1 === v2) {
    return options.fn(this);
  }
  return options.inverse(this);
});

Możesz następnie wywołać helpera w szablonie w następujący sposób

{{#ifCond v1 v2}}
    {{v1}} is equal to {{v2}}
{{else}}
    {{v1}} is not equal to {{v2}}
{{/ifCond}}
 532
Author: Nick Kitto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-10 18:24:21

Rozwiązanie idzie o krok dalej. To dodaje operatora porównania.

Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) {

    switch (operator) {
        case '==':
            return (v1 == v2) ? options.fn(this) : options.inverse(this);
        case '===':
            return (v1 === v2) ? options.fn(this) : options.inverse(this);
        case '!=':
            return (v1 != v2) ? options.fn(this) : options.inverse(this);
        case '!==':
            return (v1 !== v2) ? options.fn(this) : options.inverse(this);
        case '<':
            return (v1 < v2) ? options.fn(this) : options.inverse(this);
        case '<=':
            return (v1 <= v2) ? options.fn(this) : options.inverse(this);
        case '>':
            return (v1 > v2) ? options.fn(this) : options.inverse(this);
        case '>=':
            return (v1 >= v2) ? options.fn(this) : options.inverse(this);
        case '&&':
            return (v1 && v2) ? options.fn(this) : options.inverse(this);
        case '||':
            return (v1 || v2) ? options.fn(this) : options.inverse(this);
        default:
            return options.inverse(this);
    }
});

Użyj go w szablonie takim jak:

{{#ifCond var1 '==' var2}}

Wersja skryptu do Kawy

Handlebars.registerHelper 'ifCond', (v1, operator, v2, options) ->
    switch operator
        when '==', '===', 'is'
            return if v1 is v2 then options.fn this else options.inverse this
        when '!=', '!=='
            return if v1 != v2 then options.fn this else options.inverse this
        when '<'
            return if v1 < v2 then options.fn this else options.inverse this
        when '<='
            return if v1 <= v2 then options.fn this else options.inverse this
        when '>'
            return if v1 > v2 then options.fn this else options.inverse this
        when '>='
            return if v1 >= v2 then options.fn this else options.inverse this
        when '&&', 'and'
            return if v1 and v2 then options.fn this else options.inverse this
        when '||', 'or'
            return if v1 or v2 then options.fn this else options.inverse this
        else
            return options.inverse this
 459
Author: Jim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-05 23:31:31

Kierownica obsługuje operacje zagnieżdżone. Zapewnia to dużą elastyczność (i czystszy Kod), jeśli napiszemy naszą logikę trochę inaczej.

{{#if (or section1 section2)}}
.. content
{{/if}}

W rzeczywistości możemy dodać różne rodzaje logiki:

{{#if (or 
        (eq section1 "foo")
        (ne section2 "bar"))}}
.. content
{{/if}}

Wystarczy zarejestrować tych pomocników:

Handlebars.registerHelper({
    eq: (v1, v2) => v1 === v2,
    ne: (v1, v2) => v1 !== v2,
    lt: (v1, v2) => v1 < v2,
    gt: (v1, v2) => v1 > v2,
    lte: (v1, v2) => v1 <= v2,
    gte: (v1, v2) => v1 >= v2,
    and() {
        return Array.prototype.every.call(arguments, Boolean);
    },
    or() {
        return Array.prototype.slice.call(arguments, 0, -1).some(Boolean);
    }
});
 177
Author: kevlened,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-20 17:20:30

Dla tych, którzy żyją na krawędzi.

Gist: https://gist.github.com/akhoury/9118682 Demo : fragment kodu poniżej

Pomocnik Kierownicy: {{#xif EXPRESSION}} {{else}} {{/xif}}

Helper do wykonania instrukcji IF z dowolnym wyrażeniem

  1. wyrażenie jest odpowiednio uciekającym łańcuchem
  2. tak, musisz aby poprawnie uciec od literałów łańcuchowych lub po prostu zamienić pojedyncze i podwójne cudzysłowy
  3. możesz uzyskać dostęp do dowolnej globalnej funkcji lub właściwości tj. encodeURIComponent(property)
  4. ten przykład zakłada, że przekazałeś ten kontekst do kierownicy template( {name: 'Sam', age: '20' } ), zauważ age jest string, tylko dlatego, że mogę demo parseInt() później w tym poście

Użycie:

<p>
 {{#xif " name == 'Sam' && age === '12' " }}
   BOOM
 {{else}}
   BAMM
 {{/xif}}
</p>

Wyjście

<p>
  BOOM
</p>

JavaScript: (to zależy od innego helpera-Czytaj dalej)

 Handlebars.registerHelper("xif", function (expression, options) {
    return Handlebars.helpers["x"].apply(this, [expression, options]) ? options.fn(this) : options.inverse(this);
  });

Pomocnik Kierownicy: {{x EXPRESSION}}

Pomocnik do uruchamiania javascript wyrażenia

  1. wyrażenie jest odpowiednio uciekającym łańcuchem
  2. tak, ty potrzebujesz, aby poprawnie uciec od literałów łańcuchowych lub po prostu zamienić pojedyncze i podwójne cudzysłowy
  3. możesz uzyskać dostęp do dowolnej globalnej funkcji lub właściwości tj. parseInt(property)
  4. ten przykład zakłada, że przekazałeś ten kontekst do kierownicy template( {name: 'Sam', age: '20' } ), age jest string dla celów demo, może być cokolwiek..

Użycie:

<p>Url: {{x "'hi' + name + ', ' + window.location.href + ' <---- this is your href,' + ' your Age is:' + parseInt(this.age, 10)"}}</p>

Wyjście:

<p>Url: hi Sam, http://example.com <---- this is your href, your Age is: 20</p>

JavaScript:

To wygląda na trochę duży, ponieważ rozszerzyłem składnię i skomentowałem prawie każdą linię dla celów przejrzystości

Handlebars.registerHelper("x", function(expression, options) {
  var result;

  // you can change the context, or merge it with options.data, options.hash
  var context = this;

  // yup, i use 'with' here to expose the context's properties as block variables
  // you don't need to do {{x 'this.age + 2'}}
  // but you can also do {{x 'age + 2'}}
  // HOWEVER including an UNINITIALIZED var in a expression will return undefined as the result.
  with(context) {
    result = (function() {
      try {
        return eval(expression);
      } catch (e) {
        console.warn('•Expression: {{x \'' + expression + '\'}}\n•JS-Error: ', e, '\n•Context: ', context);
      }
    }).call(context); // to make eval's lexical this=context
  }
  return result;
});

Handlebars.registerHelper("xif", function(expression, options) {
  return Handlebars.helpers["x"].apply(this, [expression, options]) ? options.fn(this) : options.inverse(this);
});

var data = [{
  firstName: 'Joan',
  age: '21',
  email: '[email protected]'
}, {
  firstName: 'Sam',
  age: '18',
  email: '[email protected]'
}, {
  firstName: 'Perter',
  lastName: 'Smith',
  age: '25',
  email: '[email protected]'
}];

var source = $("#template").html();
var template = Handlebars.compile(source);
$("#main").html(template(data));
h1 {
  font-size: large;
}
.content {
  padding: 10px;
}
.person {
  padding: 5px;
  margin: 5px;
  border: 1px solid grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0/handlebars.min.js"></script>

<script id="template" type="text/x-handlebars-template">
  <div class="content">
    {{#each this}}
    <div class="person">
      <h1>{{x  "'Hi ' + firstName"}}, {{x 'lastName'}}</h1>
      <div>{{x '"you were born in " + ((new Date()).getFullYear() - parseInt(this.age, 10)) '}}</div>
      {{#xif 'parseInt(age) >= 21'}} login here:
      <a href="http://foo.bar?email={{x 'encodeURIComponent(email)'}}">
        	http://foo.bar?email={{x 'encodeURIComponent(email)'}}
        </a>
      {{else}} Please go back when you grow up. {{/xif}}
    </div>
    {{/each}}
  </div>
</script>

<div id="main"></div>

Moar

Jeśli chcesz uzyskać dostęp do zakresu górnego poziomu, ten jest nieco inny, wyrażenie jest połączeniem wszystkich argumentów, użycie: powiedzmy dane kontekstowe wyglądają tak:

// data
{name: 'Sam', age: '20', address: { city: 'yomomaz' } }

// in template
// notice how the expression wrap all the string with quotes, and even the variables
// as they will become strings by the time they hit the helper
// play with it, you will immediately see the errored expressions and figure it out

{{#with address}}
    {{z '"hi " + "' ../this.name '" + " you live with " + "' city '"' }}
{{/with}}

Javascript:

Handlebars.registerHelper("z", function () {
    var options = arguments[arguments.length - 1]
    delete arguments[arguments.length - 1];
    return Handlebars.helpers["x"].apply(this, [Array.prototype.slice.call(arguments, 0).join(''), options]);
});

Handlebars.registerHelper("zif", function () {
    var options = arguments[arguments.length - 1]
    delete arguments[arguments.length - 1];
    return Handlebars.helpers["x"].apply(this, [Array.prototype.slice.call(arguments, 0).join(''), options]) ? options.fn(this) : options.inverse(this);
});
 89
Author: bentael,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-15 16:07:03

Jest prosty sposób, aby to zrobić bez pisania funkcji pomocniczej... Można to zrobić całkowicie w szablonie.

{{#if cond1}}   
  {{#if con2}}   
    <div> and condition completed</div>  
  {{/if}}
{{else}}   
  <div> both conditions weren't true</div>  
{{/if}}

Edit: odwrotnie można to zrobić lub zrobić:

{{#if cond1}}  
  <div> or condition completed</div>    
{{else}}   
  {{#if cond2}}  
    <div> or condition completed</div>  
  {{else}}      
    <div> neither of the conditions were true</div>    
  {{/if}}  
{{/if}}

Edit / Note: From the handlebar ' s website: handlebarsjs.com oto wartości falsy:

Możesz użyć helpera if do warunkowego renderowania bloku. Jeśli jego argument zwraca false, undefined, null, ""lub [] (wartość "falsy"), Wtedy każdy " cond "( jak cond1 lub cond2) nie zostaną uznane za prawdziwe.

 34
Author: Jono,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-13 04:41:01

Jednym z problemów ze wszystkimi odpowiedziami zamieszczonymi tutaj jest to, że nie działają one z powiązanymi właściwościami, tzn. warunek if nie jest ponownie oceniany, gdy właściwości te ulegną zmianie. Oto nieco bardziej zaawansowana wersja helpera obsługującego wiązania. Wykorzystuje ona funkcję bind ze źródła Ember, która jest również używana do implementacji zwykłego helpera Ember #if.

Ta jest ograniczona do pojedynczej własności po lewej stronie, w porównaniu do stałej na prawa strona, która moim zdaniem jest wystarczająco dobra dla większości praktycznych celów. Jeśli potrzebujesz czegoś bardziej zaawansowanego niż proste porównanie, być może dobrze byłoby zacząć deklarować niektóre właściwości obliczeniowe i używać zwykłego helpera #if.

Ember.Handlebars.registerHelper('ifeq', function(a, b, options) {
  return Ember.Handlebars.bind.call(options.contexts[0], a, options, true, function(result) {
    return result === b;
  });
});

Możesz go użyć Tak:

{{#ifeq obj.some.property "something"}}
  They are equal!
{{/ifeq}}
 19
Author: devongovett,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-12 07:41:33

Ulepszone rozwiązanie, które zasadniczo działa z dowolnym operatorem binarnym (przynajmniej cyfry, łańcuchy nie działają dobrze z eval, zadbaj o ewentualne wstrzyknięcie skryptu, jeśli użyjesz nieokreślonego operatora z wejściami użytkownika):

Handlebars.registerHelper("ifCond",function(v1,operator,v2,options) {
    switch (operator)
    {
        case "==":
            return (v1==v2)?options.fn(this):options.inverse(this);

        case "!=":
            return (v1!=v2)?options.fn(this):options.inverse(this);

        case "===":
            return (v1===v2)?options.fn(this):options.inverse(this);

        case "!==":
            return (v1!==v2)?options.fn(this):options.inverse(this);

        case "&&":
            return (v1&&v2)?options.fn(this):options.inverse(this);

        case "||":
            return (v1||v2)?options.fn(this):options.inverse(this);

        case "<":
            return (v1<v2)?options.fn(this):options.inverse(this);

        case "<=":
            return (v1<=v2)?options.fn(this):options.inverse(this);

        case ">":
            return (v1>v2)?options.fn(this):options.inverse(this);

        case ">=":
         return (v1>=v2)?options.fn(this):options.inverse(this);

        default:
            return eval(""+v1+operator+v2)?options.fn(this):options.inverse(this);
    }
});
 12
Author: Vincent,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-21 16:05:02

Oto rozwiązanie, jeśli chcesz sprawdzić wiele warunków:

/* Handler to check multiple conditions
   */
  Handlebars.registerHelper('checkIf', function (v1,o1,v2,mainOperator,v3,o2,v4,options) {
      var operators = {
           '==': function(a, b){ return a==b},
           '===': function(a, b){ return a===b},
           '!=': function(a, b){ return a!=b},
           '!==': function(a, b){ return a!==b},
           '<': function(a, b){ return a<b},
           '<=': function(a, b){ return a<=b},
           '>': function(a, b){ return a>b},
           '>=': function(a, b){ return a>=b},
           '&&': function(a, b){ return a&&b},
           '||': function(a, b){ return a||b},
        }
      var a1 = operators[o1](v1,v2);
      var a2 = operators[o2](v3,v4);
      var isTrue = operators[mainOperator](a1, a2);
      return isTrue ? options.fn(this) : options.inverse(this);
  });

Użycie:

/* if(list.length>0 && public){}*/

{{#checkIf list.length '>' 0 '&&' public '==' true}} <p>condition satisfied</p>{{/checkIf}}
 8
Author: Sateesh Kumar Alli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-07 10:55:18

Oto link do bloku helpera, którego używam: comparison Block helper . Obsługuje wszystkie standardowe operatory i pozwala pisać kod, jak pokazano poniżej. Jest bardzo poręczny.

{{#compare Database.Tables.Count ">" 5}}
There are more than 5 tables
{{/compare}}
 7
Author: CleanTheRuck,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-24 14:40:30

Podobne do odpowiedzi Jima, ale przy odrobinie kreatywności moglibyśmy też zrobić coś takiego:

Handlebars.registerHelper( "compare", function( v1, op, v2, options ) {

  var c = {
    "eq": function( v1, v2 ) {
      return v1 == v2;
    },
    "neq": function( v1, v2 ) {
      return v1 != v2;
    },
    ...
  }

  if( Object.prototype.hasOwnProperty.call( c, op ) ) {
    return c[ op ].call( this, v1, v2 ) ? options.fn( this ) : options.inverse( this );
  }
  return options.inverse( this );
} );

Następnie, aby go użyć, otrzymujemy coś w stylu:

{{#compare numberone "eq" numbretwo}}
  do something
{{else}}
  do something else
{{/compare}}

Sugerowałbym przeniesienie obiektu z funkcji dla lepszej wydajności, ale w przeciwnym razie można dodać dowolną funkcję porównania, w tym "and "I " or".

 4
Author: ars265,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-19 04:12:27

Inną alternatywą jest użycie nazwy funkcji w #if. #if wykryje, czy parametr jest funkcją, a jeśli tak, to wywoła go i użyje jego zwrotu do sprawdzenia prawdziwości. Poniżej moja funkcja Pobiera bieżący kontekst jako this.

{{#if myFunction}}
  I'm Happy!
{{/if}}
 3
Author: Shital Shah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-08 08:57:01

Niestety żadne z tych rozwiązań nie rozwiązuje problemu "lub" operatora "cond1 / / cond2".

  1. Sprawdź, czy pierwsza wartość jest prawdziwa
  2. Użyj " ^ " (or) i sprawdź, czy inaczej cond2 jest prawdziwe

    {{#if cond1}} WYKONAJ AKCJĘ {{^}} {{#if cond2}} WYKONAJ AKCJĘ {{/if}} {{/if}}

Łamie zasadę suchości. Więc dlaczego nie użyć częściowego, aby uczynić go mniej brudnym
{{#if cond1}}
    {{> subTemplate}}
{{^}}
    {{#if cond2}}
        {{> subTemplate}}
    {{/if}}
{{/if}}
 3
Author: Pawel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-03 14:13:38

Mogę zrozumieć, dlaczego chcesz stworzyć helpera w sytuacjach, w których masz dużą liczbę różnych porównań do wykonania w szablonie, ale dla stosunkowo małej liczby porównań (lub nawet jednego, co doprowadziło mnie do tej strony w pierwszej kolejności), prawdopodobnie łatwiej byłoby zdefiniować nową zmienną kierownicy w wywołaniu funkcji renderowania widoku, jak:

Przejście do kierownicy przy renderowaniu:

var context= {
    'section1' : section1,
    'section2' : section2,
    'section1or2' : (section1)||(section2)
};

A potem w kierownicy szablon:

{{#if section1or2}}
    .. content
{{/if}}
Wspominam o tym ze względu na prostotę, a także dlatego, że jest to odpowiedź, która może być szybka i pomocna, a jednocześnie zgodna z logiczną naturą kierownicy.
 3
Author: Programmer Dan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-25 19:00:33

Zainstaluj Ember Helpers {[4] } addon uruchamiając poniższe polecenie

Ember install ember-truth-helpers

Możesz zacząć używać większości operatorów logicznych (eq, not-EQ, not, and, or, gt,gte,lt,lte, xor).

{{#if (or section1 section2)}}  
...content  
{{/if}}

Możesz nawet dodać podwyrażenie, aby pójść dalej,

{{#if (or (eq section1 "section1") (eq section2 "section2") ) }}  
...content  
{{/if}}
 3
Author: Ember Freak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-20 17:07:30

Jeszcze jedno krzywe rozwiązanie dla trójdzielnego pomocnika:

'?:' ( condition, first, second ) {
  return condition ? first : second;
}

<span>{{?: fooExists 'found it' 'nope, sorry'}}</span>

Lub prosty Pomocnik koalesce:

'??' ( first, second ) {
  return first ? first : second;
}

<span>{{?? foo bar}}</span>

Ponieważ znaki te nie mają specjalnego znaczenia w znacznikach kierownicy, możesz ich używać do nazw pomocników.

 3
Author: Moritz Friedrich,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-15 13:01:36

Znalazłem pakiet npm wykonany z CoffeeScript, który ma wiele niesamowitych przydatnych pomocników dla kierownicy. Zapoznaj się z dokumentacją pod następującym adresem URL:

Https://npmjs.org/package/handlebars-helpers

Możesz wykonać wget http://registry.npmjs.org/handlebars-helpers/-/handlebars-helpers-0.2.6.tgz, aby je pobrać i zobaczyć zawartość pakietu.

Będziesz mógł robić rzeczy takie jak {{#is number 5}} lub {{formatDate date "%m/%d/%Y"}}

 2
Author: Cristian Rojas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-11 15:21:46

Jeśli chcesz tylko sprawdzić, czy jeden lub drugi element jest obecny, możesz użyć tego custom helpera

Handlebars.registerHelper('if_or', function(elem1, elem2, options) {
  if (Handlebars.Utils.isEmpty(elem1) && Handlebars.Utils.isEmpty(elem2)) {
    return options.inverse(this);
  } else {
    return options.fn(this);
  }
});

Like this

{{#if_or elem1 elem2}}
  {{elem1}} or {{elem2}} are present
{{else}}
  not present
{{/if_or}}

Jeśli musisz również mieć" or " do porównania wartości zwracane przez funkcję Wolałbym dodać kolejną właściwość, która zwraca pożądany wynik.

Szablony powinny być jednak bez logiki!

 1
Author: deepflame,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:33:24

Dla tych, którzy mają problemy z porównaniem właściwości obiektu, wewnątrz helpera dodaj to rozwiązanie

Ember.js helper nie rozpoznaje poprawnie parametru

 1
Author: Manuel Cepeda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:54

Właśnie przyszedł do tego postu z wyszukiwarki google, jak sprawdzić, czy ciąg jest równy innemu ciągowi.

Używam HandlebarsJS po stronie serwera NodeJS, ale używam również tych samych plików szablonów z przodu, używając wersji przeglądarki HandlebarsJS, aby je przeanalizować. Oznacza to, że gdybym chciał custom helpera, musiałbym go zdefiniować w 2 oddzielnych miejscach lub przypisać funkcję do danego obiektu - zbyt duży wysiłek!!

Ludzie zapominają, że pewne obiekty dziedziczą funkcje które można wykorzystać w szablonie wąsy. W przypadku ciągu znaków:

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

An Array containing the entire match result and any parentheses-captured matched results; null if there were no matches.

Możemy użyć tej metody, aby zwrócić tablicę dopasowań, lub null Jeśli nie znaleziono dopasowań. Jest to idealne rozwiązanie, ponieważ patrząc na dokumentację kierownicy http://handlebarsjs.com/builtin_helpers.html

You can use the if helper to conditionally render a block. If its argument returns false, undefined, null, "", 0, or [], Handlebars will not render the block.

Więc...

{{#if your_string.match "what_youre_looking_for"}} 
String found :)
{{else}}
No match found :(
{{/if}}

UPDATE:

Po przetestowaniu na wszystkich przeglądarkach, to nie działa na Firefoksie. HandlebarsJS przekazuje inne argumenty do wywołania funkcji, co oznacza, że gdy String.prototyp.wywołana jest match, drugi argument (tzn. flagi Regexp dla wywołania funkcji match, zgodnie z powyższą dokumentacją) wydaje się być przekazywany. Firefox postrzega to jako przestarzałe użycie Sznurek.prototyp.mecz, a więc przerwy.

Obejście polega na zadeklarowaniu nowego funkcjonalnego prototypu dla obiektu String JS , a zamiast tego użyć tego:

if(typeof String.includes !== 'function') {
    String.prototype.includes = function(str) {
        if(!(str instanceof RegExp))
            str = new RegExp((str+'').escapeRegExp(),'g');
        return str.test(this);
    }
}

Upewnij się, że kod JS jest dołączony zanim uruchomisz kierownicę.funkcja compile (), a następnie w szablonie...

{{#your_string}}
    {{#if (includes "what_youre_looking_for")}} 
        String found :)
    {{else}}
        No match found :(
    {{/if}}
{{/your_string}}
 1
Author: Jon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-03 22:12:33

Tutaj mamy kilka logicznych & & i / / (I or):

Handlebars.registerHelper("and",function() {
    var args = Array.prototype.slice.call(arguments);
    var options = args[args.length-1];

    for(var i=0; i<args.length-1; i++){
        if( !args[i] ){
            return options.inverse(this);
        }
    }

    return options.fn(this);
});


Handlebars.registerHelper("or",function() {
    var args = Array.prototype.slice.call(arguments);
    var options = args[args.length-1];

    for(var i=0; i<args.length-1; i++){
        if( args[i] ){
            return options.fn(this);
        }
    }

    return options.inverse(this);
}

// Results
// {{#and foo bar sally bob}} yup {{else}} nope {{/and}} // yup
// {{#or foo bar "" sally bob}} yup {{else}} nope {{/or}} // yup

// {{#and foo bar "" sally bob}} yup {{else}} nope {{/and}} // nope
// {{#or "" "" "" "" ""}} yup {{else}} nope {{/or}} // nope

Nie jestem pewien, czy jest to" bezpieczne "w użyciu" i "i"lub"... może zmienić na coś w rodzaju "op_and" i "op_or"?

 1
Author: bob,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-18 14:42:41

Prawidłowe rozwiązanie dla i / lub

Handlebars.registerHelper('and', function () {
    // Get function args and remove last one (function name)
    return Array.prototype.slice.call(arguments, 0, arguments.length - 1).every(Boolean);
});
Handlebars.registerHelper('or', function () {
    // Get function args and remove last one (function name)
    return Array.prototype.slice.call(arguments, 0, arguments.length - 1).some(Boolean);
}); 

Następnie wywołaj w następujący sposób

{{#if (or (eq questionType 'STARTTIME') (eq questionType 'ENDTIME') (..) ) }}

BTW: zauważ, że podane tutaj rozwiązanie jest nieprawidłowe, nie odejmuje ostatniego argumentu, który jest nazwą funkcji. https://stackoverflow.com/a/31632215/1005607

Jego Oryginał i/lub został oparty na pełnej liście argumentów

   and: function () {
        return Array.prototype.slice.call(arguments).every(Boolean);
    },
    or: function () {
        return Array.prototype.slice.call(arguments).some(Boolean);
    }
Czy ktoś może zmienić tę odpowiedź? Właśnie zmarnowałem godzinę próbując naprawić coś w odpowiedzi zalecanej przez 86 osób. Naprawa polega na filtruje ostatni argument , który jest nazwą funkcji. Array.prototype.slice.call(arguments, 0, arguments.length - 1)
 1
Author: gene b.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-05 16:06:47

Podążając za tymi 2 przewodnikami a-way-to-let-users-define-custom-made-bound-if-statements i custom bound helpers byłem w stanie dostosować moje wspólne widoki w tym poście na stackoverflow Aby użyć tego zamiast standardowej instrukcji #if. To powinno być bezpieczniejsze niż rzucanie tam # if.

Custom bound helpers w tym gist są wybitne.

<li>
    <a href="{{unbound view.varProductSocialBlog}}">
        {{#if-equal view.showDiv "true"}}<div>{{/if-equal}}<i class="fa fa-rss-square"></i>{{#if-equal view.showDiv "true"}}</div>{{/if-equal}}
        {{#if-equal view.showTitle "true"}}Blog{{/if-equal}}
    </a>
</li>

Używam projektu ember cli do budowy mojego ember podanie.

Aktualna konfiguracja w czasie tego postu:

DEBUG: -------------------------------
DEBUG: Ember      : 1.5.1
DEBUG: Ember Data : 1.0.0-beta.7+canary.b45e23ba
DEBUG: Handlebars : 1.3.0
DEBUG: jQuery     : 2.1.1
DEBUG: -------------------------------
 0
Author: Chris Hough,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:33:24

W Ember.js możesz użyć inline if helper in if Block helper. Może zastąpić || operator logiczny, na przykład:

{{#if (if firstCondition firstCondition secondCondition)}}
  (firstCondition || (or) secondCondition) === true
{{/if}}
 0
Author: Daniel Kmak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-12 10:53:02

Możesz to zrobić po prostu używając operatora logicznego, jak pokazano poniżej:

{{#if (or(eq firstValue 'String_to_compare_value') (eq secondValue 'String_to_compare_value'))}}business logic goes here{{/if}}

{{#if (and(eq firstValue 'String_to_compare_value') (eq secondValue 'String_to_compare_value'))}}business logic goes here{{/if}}

Przed zamknięciem jeśli możesz napisać swoją logikę biznesową

 0
Author: Kunwar Babu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-02 01:01:30

Możesz użyć następującego kodu:

{{#if selection1}}
    doSomething1
{{else}}
   {{#if selection2}}
       doSomething2
   {{/if}}
{{/if}}
 0
Author: Varuni Punchihewa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-31 15:42:09

Oto podejście, którego używam dla ember 1.10 i ember-cli 2.0.

// app/helpers/js-x.js
export default Ember.HTMLBars.makeBoundHelper(function (params) {
  var paramNames = params.slice(1).map(function(val, idx) { return "p" + idx; });
  var func = Function.apply(this, paramNames.concat("return " + params[0] + ";"))
  return func.apply(params[1] === undefined ? this : params[1], params.slice(1));
});

Następnie możesz użyć go w swoich szablonach w następujący sposób:

// used as sub-expression
{{#each item in model}}
  {{#if (js-x "this.section1 || this.section2" item)}}
  {{/if}}
{{/each}}

// used normally
{{js-x "p0 || p1" model.name model.offer.name}}

Gdzie argumenty do wyrażenia są przekazywane jako p0,p1,p2 etc i p0 mogą być również określane jako this.

 -1
Author: Michael,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-26 03:36:02