我一直在寻找如何大写字符串中每个单词的第一个字符,但没有任何帮助。我需要将输入的字符串设置为大写小写的标题。我已经试过了:
function titleCase(str) {
//converting the giving string into array
str =str.split(" ");
//iterating over all elem.s in the array
for(var i=0;i<str.length;i++){
//converting each elem. into string
str[i]=str[i].toString();
//converting the first char to upper case &concatenating to the rest chars
str[i]=str[i].toUpperCase(str[i].charAt(0))+ str[i].substring(1);
}
return str;
}
titleCase("I'm a little tea pot");Run Code Online (Sandbox Code Playgroud)
我经常在 django 模板中使用 django-cms 做这样的事情:
{% load cms_tags %}
<a href="{% page_url 'imprint' %}">Imprint</a>
Run Code Online (Sandbox Code Playgroud)
在生产环境中,此操作会默默失败,并且 href 属性为空。在开发中,我被迫插入 id 为“imprint”的页面,否则我会收到“DoesNotExist”异常。
我该如何改善这种情况?也许我正在寻找类似的东西
{% if 'imprint'|cms_page_exists %}
...the link and stuff...
Run Code Online (Sandbox Code Playgroud)
对于这个(并不罕见)用例,是否有已知的最佳实践?还是大家都是按照第一个所示的方式使用的?
如果以结尾,我需要渲染图像adobe_illustrator_file_logo.png。file.url.ai
但如果file.url以其他终止方式结束,.png例如 example,我将渲染该对象的图像。
我已经搜索过文档,但显然没有endswith内置过滤器。
所以我最终玩了ifequals过滤slice器。
逻辑是相同的:“如果字符串与最后 3 个字母相同,则执行此操作”。
但是,它不起作用,因为没有显示任何内容。
<td>
{% ifequal cart_item.file.url|default:""|slice:"-3" ".ai" %}
<img src="{% static 'img/admin/adobe_illustrator_file_logo.png' %}"
alt=""
class="float-left rounded custom_image">
{% endifequal %}
</td>
Run Code Online (Sandbox Code Playgroud)
笔记:
<p>{{ cart_item.file.url }}</p>
Run Code Online (Sandbox Code Playgroud)
HTML 呈现:
<p>/media/files/working_precisely.ai</p>
Run Code Online (Sandbox Code Playgroud)
此外,如果将adobe_illustrator_file_logo.png放在 if 条件之外,它也会正确呈现。
更新1:
创建了我自己的过滤器,但出现错误:
/cart/
endswith 处的 TemplateSyntaxError 需要 2 个参数,已提供 1 个
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter(is_safe=False) …Run Code Online (Sandbox Code Playgroud)