2

I have an amp-list which loads bunch of data and I show them in their respective placeholders just nice and easy. What I intend to do is get a value and run a simple script on it. Let's think I have

<div>{{title}}</div>

where title is: 'This-is-my-title'

now I would like to replace the '-' in title, I know I could do it with javascript using title.replace(/-/g,' '), how can I do that in place? I tried

<div>{{title.replace(/-/g,' ')}}</div>

but no luck :(

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Amir Shahbabaie
  • 1,352
  • 2
  • 14
  • 33

2 Answers2

2

In plain javascript the following:

title = 'This-is-my-title'; title.replace(/-/g, ' '); 

gives you "This is my title".

I am guessing you are using angular, in that case the text within {{ }} is not evaluated as a pure javascript expression. You could write an angular filter to apply to the expresssion (as described in Angular filter to replace all underscores to spaces ). It would probably be easier to handle this in the controller behind the template. Something like:

$scope.title = $scope.title.replace(/-/g,' ');
2

Looks like you are using amp-mustache. I don't think there is a way for you to use custom JavaScript in Mustache.js here, and restrictions from AMP prevent you to create some kind of function that you can call in {{}}. I would suggest processing in the backend before sending. (Also unfortunately, there are no other templates other than mustache available at this point)

There is a workaround on math using amp-bind here: AMP Mustache and Math So probably after loading the JSON with amp-state, something like

myItems.map(entry => ({
  myString: entry.myString.split('').map(c => c == '-' ? ' ' : c).join('')),
})

might work (I have not tested myself but worth a try, check whitelisted functions here: https://www.ampproject.org/es/docs/reference/components/amp-bind#white-listed-functions) but might still be a pain performance-wise (amp-bind has quite a bit overhead)

Edit: this actually looks quite promising, just found out actually amp-list with amp-bind do accept object for [src], as described in the doc (learning something new myself): https://www.ampproject.org/docs/reference/components/amp-bind (checked amp-list source code and should work)

Kevin Qian
  • 2,532
  • 1
  • 16
  • 26