Search code examples
javascripthtmlamp-htmlaccelerated-mobile-pagegoogle-amp

How to dynamically add a new line to the string stored in the AMP state?


I'm learning to work with the Accelerated Mobile Pages. I want to add a new line and some text content to a string, stored in the amp-state, when the user presses button. So I have tried this:

<script src="https://cdn.ampproject.org/v0.js"></script>
<script src="https://cdn.ampproject.org/v0/amp-bind-0.1.js"></script>

<amp-state id="formState">
  <script type="application/json">
    {
      "message": "Some text"
    }
  </script>
</amp-state>

<textarea [text]="formState.message"></textarea>

<button type="button"
  on="tap:AMP.setState({formState: {message: formState.message + '\nSome another text'} })">
  Button
</button>

Unfortunately, it seems that it somehow escapes the \ character. So I literally got Some text\nSome another text in the textarea.

I have tried String.fromCharCode and so on, but it is prohibited in the AMP... got stuck with this.

I can't find much documentation on this use case, so asking here: is there any way to dynamically add a new line to the string, stored in the amp-state, on the user interaction?


Solution

  • Define the newline:

    <amp-state id="formState">
      <script type="application/json">
      {
        "message": "Some text",
        "newLine": "\n"
      }
      </script>
    </amp-state>
    

    then:

     on="tap:AMP.setState({formState: {message: formState.message + formState.newLine + 'asdf'} })">