简体   繁体   English

新行不从 HTML 中的模板标签呈现

[英]New line not rendering from template tag in HTML

I have a set of information to be rendered on my webpage using django template tags.我有一组信息要使用 django 模板标签呈现在我的网页上。

 {% for product in sales %}

      <div>
        <span>Customer:{{product.to_user}}</span><br>
        <span>{{product.time}}</span><br>
        <p class="message">{{product.message}}</p>
      </div>

      {% endfor %}

The {{product.message}} template tag contains information separated by new line('\\n'). {{product.message}}模板标签包含由新行('\\n')分隔的信息。 But, newlines are not rendered in HTML, the information is displayed in a single line omitting to obey '\\n'.但是,换行符不在 HTML 中呈现,信息显示在单行中,省略了 '\\n'。 I tried capturing the information from the <p> tag and replacing \\n , with <br> , and again setting the text in the same <p> tag.我尝试从<p>标签中捕获信息并用<br>替换\\n ,然后再次在同一个<p>标签中设置文本。 But it doesn't seem to work.但它似乎不起作用。
This was my approach, as stated above.这是我的方法,如上所述。

$(document).ready(function(){

      let renderedText = $(".message").text()

      //alert(renderedText)
      final_txt = renderedText.replace(/\n/g,"<br>")

      $(".message").val(final_txt)
       
    })

What changes or addition should I make, in order to get this working?我应该进行哪些更改或添加,以使其正常工作? Thanks in advance.提前致谢。

像这样使用模板过滤器linebreaksbr

<p class="message">{{ product.message|linebreaksbr }}</p>

In order to have the line information you can use pre tag to keep track of empty spaces and new line.为了获得行信息,您可以使用pre 标记来跟踪空格和新行。

 let message = `Lorem ipsum text Lorem ipsum text Lorem ipsum text. Lorem ipsum textLorem ipsum text Lorem ipsum textLorem ipsum textLorem ipsum textLorem ipsum textLorem ipsum textLorem ipsum textLorem ipsum textLorem ipsum textLorem ipsum text`;
 <div><pre>{message}</pre></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM