Шаблонизация с javascript
http://ejohn.org/blog/javascript-micro-templating/
Есть одна утилитка, которой я уже пользуюсь некоторое время, довольно полезная при построении javascript-приложений. Это - супер-простая и очень быстрая функция для шаблонизации на клиенте. Она предложена Джоном Ресигом.
Я применяю ее для постраничной навигации и для небольших шаблонов в AJAX-приложениях с подгрузкой данных с сервера.
Вот исходный код функции шаблонизатора:
(function(){
var cache = {};
this.tmpl = function tmpl(str, data){
// Выяснить, мы получаем шаблон или нам нужно его загрузить
// обязательно закешировать результат
var fn = !/\W/.test(str) ?
cache[str] = cache[str] ||
tmpl(document.getElementById(str).innerHTML) :
// Сгенерировать (и закешировать) функцию,
// которая будет служить генератором шаблонов
new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
// Сделать данные доступными локально при помощи with(){}
"with(obj){p.push('" +
// Превратить шаблон в чистый JavaScript
str
.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'")
+ "');}return p.join('');");
// простейший карринг(термин функ. прог. - прим. пер.)
// для пользователя
return data ? fn( data ) : fn;
};
})();
Её можно использовать с шаблонами, написанными в таком виде (не обязательно точно в таком, но этот стиль мне нравится):
<script type="text/html" id="item_tmpl">
<div id="<%=id%>" class="<%=(i % 2 == 1 ? " even" : "")%>">
<div class="grid_1 alpha right">
<img class="righted" src="<%=profile_image_url%>"/>
</div>
<div class="grid_6 omega contents">
<p><b><a href="/<%=from_user%>"><%=from_user%></a>:</b> <%=text%></p>
</div>
</div>
</script>
Вы также можете сделать скриптовую вставку:
<script type="text/html" id="user_tmpl">
<% for ( var i = 0; i < users.length; i++ ) { %>
<li><a href="<%=users[i].url%>"><%=users[i].name%></a></li>
<% } %>
</script>
<script type="text/html">
Скрипты с неизвестным типом содержания type (как в примере выше - браузер не знает что делать с text/html -скриптом) просто игнорируются браузерами и поисковиками.
Это замечательный способ незаметной вставки шаблонов в страницу. Мне нравится такая техника для случаев, когда нужно быстро вставить один-другой небольшой шаблон.
А вызов шаблонки из скрипта - примерно такой:
var results = document.getElementById("results");
results.innerHTML = tmpl("item_tmpl", dataObject);
Вы можете прекомпилировать результат для дальнейшего использования. Если Вы вызываете функцию-шаблонизатор только с ID(или кодом шаблона) - она вернет прекомпилированную функцию, которую Вы можете запускать, когда угодно:
var show_user = tmpl("item_tmpl"), html = "";
for ( var i = 0; i < users.length; i++ ) {
html += show_user( users[i] );
}
Самая большая проблема этого метода, на текущий момент - это код парсинга/конвертации. Он использует много регулярных выражений и его можно улучшить.
Однако, он использует одну технику, которая мне очень нравится - а именно: если Вы делаете поиск-и-замену фиксированных подстрок, то быстрее всех с этим справляется .split("match").join("replace") .
Это неочевидно, но так оно работает быстрее всего в большинстве современных браузеров.
Играйте с этим кодом, как захотите - мне даже любопытно, во что он может превратиться. Он очень прост - и по идее, с ним можно сделать многое.
|
Чуть не забыл - когда шаблоны пишете - обязательно везде ставить точки с запятой и не использовать комментов //
Т.к весь шаблон функция превращает в одну строку в итоге - будут синтаксические ошибки без точек с запятой.
Эту шаблонку можно по-разному модифицировать, я использую чуть упрощенный вариант:
Вызвать компиляцию шаблона и тут же получить результат для
data
можно так:А вот так не скушает
Надо без точки с запятой в таких конструкциях.
Cuffie Wireless Bluetooth 5.0 Senza Fili Bassi Potenziati, Auricolari con Custodia da Ricarica 25 Ore di Utilizzo, Microfoni Integrati,Touch Control per Samsung iPhone Huawei - Utilizzo StandAlone
Я бы сделал даже так:
Мы ведь говорим о RIA...
А разве нельзя в шаблонах использовать комменты следующего вида?
Мне кажется, что после сборки в одну строку комментарий такого вида не должен мешать выполнению скрипта, к тому же, можно удалять его через всё тот же RegExp... (с чем у меня, правда говоря, проблемы - пока не возникало большой необходимости его изучать)
Угу, такой комментарий вполне подойдет.
Извините, конечно, но это семиколесный велосипед. Его много раз изобретали до вас. И он конечно ездит. Но недалеко.
Есть куча js-фреймворков, превращающих маниуляции с DOM в детскую игру. Есть XSLT выполняемый непосредственно броузеорм или через JS. И в конце концов есть куча бесплатных или очень дешевых хостингов с php/.NET/phyton...
Вещь хорошая ездит замечательно. Пользуюсь нравится.
Про php/.NET/python - это Вы в сторону далеко ушли. Тут именно JS-шаблонка. Для своих задач. Возможно, их у Вас пока не возникало, возникнут - вспомните, придете на эту страничку
P.S А XSLT на уровне браузера - мало того что куча несовместимостей, так оно еще и убогое, без EXSLT.
для чего вообще это нужно?
взял ваши примеры реализовал все работает гладко, мне понравилось
Эта функция шаблонизации не будет работать в ASP-страницах.
Дело в том, что дескрипторы начала (<%=) и конца (%>) шаблона уже зарезервированы ASP-движком.
Точно. На таких страницах лучше бы поправить <%= .. %> на что-нибудь другое.. Например, на <?= ... ?>
мсье шутить изволит))
Зачем в серверном языке джаваскрипт-шаблоны ? :\
А как сделать, чтоб при нажатии на кнопку появлялось окошко с текстом?(что надо в скрипте написать?)
(что надо здесь написать?)("действие")
Спасибо за информацию.
Вопрос, не могу решить куда поместить шаблон, когда он необходим при реализации плагина/библиотеки...
Не хочется каждый раз копи-пастить шаблон в новый проект, где будет использоватся библиотека...
Присоединяюсь к последнему вопросу. Если у меня многострочный шаблон, использующийся в двух-трех разных местах. Какие способы организации хранения и получения шаблонов?
Это уже вопросы к вашему движку и фреймворку. Javascript-шаблон - такой же шаблон как и остальные.
Удивился по поводу сказанного, что split.join работает быстрее replace.
Поэтому провел тесты.
Делал замену 10 различных значений {blahblah} в длинной строке.
Запускал в IE6 и FF3.5. Оба браузера показали преимущество функции replace. Если в FF (на маленьких итерациях) значения еще хоть куда не шли, - похожие, то в IE6 split.join работает в разы медленнее replace. На больших итерациях split.join проигрывает очень сильно и в FF, и в IE6.
а еще можно выкинуть лишнее - функция print нигде не используется, видимо ресиг юзал её для своих целей, потом забыл выкинуть её, а все остальные тупо содрали
print=function(){p.push.apply(p,arguments);}
Функция print далеко не лишняя! Вставка переменной в шаблон осуществляется либо с помощью конструкции <%=variable%>, либо <% print (variable) %>. Второй вариант удобен в случае, например, такого шаблона:
Неплохо было бы указать назначение функции print в статье.
Вот вот, меня эта функция запутала, когда ковырял.
Собственно хотелось бы понять её смысл.
пример с шаблонизатором сделанный на основе выше предложенного ссылка на архив
У меня почему-то не работает, просто возвращает id темплейта - и все.
UPD. id шаблона должен подходить под регулярку \w+, иначе шаблонизатор принимает строку, переданную первым параметром в tmpl за шаблон, переданный текстом. Т.о. нельзя использовать дефисы в идентификаторах и такая запись не будет воспринята шаблонизатором как надо:
для использования "-" в id-шках можно переделать
!/\W/ в !/[^\w-]/
Вот если кто-то любит жквери, а еще любит шаблоны держать отдельно от страниц, то тут показано, как можно загружать внешние шаблоны http://www.clearboth.ru/article/using-external-templates-with-jquery-tem...
поясните значение $1 при реплейсинге.
Для шаблонизации я бы использовал связку js+XSLT
Самый лёгкий шаблонизатор (jQuery):
У меня тупошаблонизатор похож на предложенный в комментариях, только синтаксис ещё проще: %varname подставляет значение.
А вот реализация - чуть сложнее; при инициализации он ищет все script[type="text/x-tpl"] и складывает в массив по id. Ну и вызов - Tpl.render(myTemplateId, dataObject).
Думал над раскатыванием шаблонов в кэш js-функций, как в основном посте; на таких тупых шаблонах особого выигрыша не даёт. А совать в шаблоны логику я не стану.
Замечательно!!! Спасибо.
Можно конечно использовать существующие библиотеки, но мне нравится этот вариант.
Можно использовать несколько шаблонов, разместив их в объекте.
Это наверное пригодилось бы при работе с содержимым балунов в гугл картах.
Я заменил открывающий и закрывающий тэги в шаблоне на $[[ и ]].
It would be more wonderful if we can enjoy it right now.
google street view
I appreciate the information you share, it helps me a lot
driving directions
The article is very easy to understand, detailed and meticulous! I had a lot of harvest after watching this article from you! I find it interesting, your article gave me a new perspective! I have read many other articles on the same topic, but your article convinced me!
This is a great thing, I think everyone feels this information is very valuable, thank you
candy crush soda
good job gyus. THX.
router login
This article is great. I like it very much. Thank you!
This article is great. I like it very much. Thank you!
Your sharing is of great help to my work. I have learned a lot from this article of yours.
boxnovelicle of yours.
This article is nice. I like it. Thank you! PC Tricks
Your share is the great knowledge I have gathered, you are an important person I admire, thank you temple run 3
Found a lot of useful information, glad to join your community.
jiofi.local.html
Thanks a lot for one’s intriguing write-up. It’s actually exceptional. Searching ahead for this sort of revisions. bettas for sale
Thanks for sharing this information. I really like your blog post very much. You have really shared a informative and interesting blog post with people Road Trip Planning
Wow the blog you give us is amazing, no wonder many people want to read this. https://celebrityinsider.org/
I will recomend this blog to all of my friends. Great article.
https://happygamer.com/
Thank you for this inspiring blog. I wait for more
https://ballstepded.com/
I learned so much from this blog. Good inforamtion. https://fixoserror.com/
I wait for more.Great article.
https://premiereretail.com
I stumbled across this blog.Great article. https://tecsprint.com
Thank you for this amazing blog. Congratulations.
https://howtolose10poundsinaweek.com
The things i see here are very informative. Keep going. https://bargainistafashionista.com
I can say that is one of the best articles out on the internet. https://bankncard.com
I readed all the article. So informative https://vhan.net
This is one of the best sites i have found on the internet until now. Nice article keep going.
https://millikenconstructioninc.com/
Thanks for the information, very clear and simple. I will try to use it.Love the way you write. Working my way through your article links
https://vvhen.to/
This is one of the best articles i found on the blogs around the internet. I am really interested in seeing more of this. Keep going with the great work!
https://gzgjskpzz1m.ga
First of all ,you have picked a very unique theme . I think i might design something similar for a future project that i want to build .
On top of that ,i in truth enjoy most of your content pieces and your different point of view.
Thank you https://seoconsultants24.blogspot.com/
Nice information, many thanks to the author. It is incomprehensible to me now, but in general, the usefulness and significance is overwhelming.https://seokarma24.blogspot.com/
I have reviewed the article many times and I find it very impressive. The information is extremely useful especially the last part I care about that information very much. I have been looking for this certain information for a long time.
https://packseo.blogspot.com/
I’m gone to tell my little brother, that he should
also pay a quick visit this blog on regular basis to take updated from hottest information.
https://connectorseo.blogspot.com/
Fantastic blog! Do you have any helpful hints for aspiring writers?
I’m hoping to start my own site soon but I’m a little lost on everything.
https://sweetseo24h.blogspot.com/
I am hoping the same best effort from you in the future as well. In fact your creative writing skills has inspired me.
https://fancyseo24h.blogspot.com/
You have made some really good points there. I looked on the web to find out
more about the issue and found most individuals will go along with your views on this website
https://phoenixseogeek.com/
Nice information, many thanks to the author. It is incomprehensible to me now, but in general, the usefulness and significance is overwhelming.
https://zgjskpzz1m.ga/
Thanks for your information, it was really very helpfull 먹튀검증
Wow what a Great Information about World Day its very nice informative post. thanks for the post 대출
토토사이트 Hello! Nice to meet you. 먹튀검증First of all,안전놀이터 thank you very much for 토토사이트providing us with this variety of information. 꽁머니I think it's information that can be used in many ways. I can't imagine how much effort you've made to write this. Thank you for your hard work. I would appreciate it if you would continue to provide us with such information. In addition, COVID-19 is becoming a problem all over the world these days. I hope there's no harm to you and your family. 먹튀가디언 Thank youhttps://twiddeo.com/And, 먹튀검증토토사이트 Already 2020 is nearing the end. 메이저토토사이트 There were so many incidents this year. 사설토토 I am still feeling a lot of inconvenience and birds due to the special virus. 먹튀사이트조회It's already getting 토토사이트 a lot colder, 안전놀이터 so make sure to 먹튀검증 pack warm clothes. 먹튀요기요 Please spend the rest of https://mtygy.com/ your life happy. 메이저놀이터 Then, have a nice day!놀이터토토 https://twiddeo.com/
I've never read this kind of story before 안전놀이터. What a great story! I read it really interestingly.As much as I find it interesting, I think you can be impressed with my 토토커뮤니티. My site name is 토토커뮤니티사이트. Please visit!!
Your post is very interesting to me. I had so much fun reading. I do a similar kind of posting. Please visit my site once. The site name Is 안전놀이터.In general, there are a lot of materials related to 토토커뮤니티. If you have time, please visit my site 토토커뮤니티사이트!
What kind of article do you like?? If someone asks, they will say that they like the article related to 안전놀이터 just like your article. If you are interested in my writing, please visit 메이저놀이터!!
Nice to meet you. Your post was really impressive. It's an unexpected idea. It was a great stimulus to me.How did you come up with 안전한놀이터 this genius idea? Your writing ability is amazing. Like me, you may be interested in my writing. If you want to see my article, please come to 안전놀이터!!
This is highly information, crisp and clear. You have a way of writing compelling information that sparks much interest.
https://larkenequity.com/ https://larkenequity.com//
Wow very good post, please dont stop posting things like this because ie really enjoy this
https://hrma-llc.com/
https://hrma-llc.com/
You are a very persuasive writer. I can see this in your article. You have a way of writing compelling information that sparks much interest.
https://nuestropsicologoenmadrid.com/
https://nuestropsicologoenmadrid.com/
I wish more authors of this type of content Wow.!This is highly information, crisp and clear. You have a way of writing compelling information that sparks much interest.!!!
https://cremationconsultancy.com/ https://cremationconsultancy.com//
This is very educational content and written well for a change. It's nice to see that some people still understand how to write a quality post!
https://i-repaircenter.nl/
https://i-repaircenter.nl/
I really thank you for the valuable info on this great subject and look forward to more great posts. Thanks a lot for enjoying this beauty article with me.
https://zoekmachineservices.nl/
https://zoekmachineservices.nl/
I do not know what to say really what you share very well and useful to the community, I feel that it makes our community much more developed
https://hetonderdelenhuis-emmen.nl/ https://hetonderdelenhuis-emmen.nl/
This is very educational content and written well for a change. It's nice to see that some people still understand how to write a quality post!
https://casinoonline-bet.com/
https://casinoonline-bet.com/
Great post! I am actually getting ready to across this information, is very helpful my friend. Also great blog here with all of the valuable information you have. Keep up the good work you are doing here
https://restorationdoctorva.com/
https://restorationdoctorva.com/
You are a very persuasive writer. I can see this in your article. You have a way of writing compelling information that sparks much interest.
https://fixoserror.com/
https://fixoserror.com/
Wow very good post, please dont stop posting things like this because ie really enjoy this
https://vvhen.to/
https://vvhen.to/
You are a very persuasive writer. I can see this in your article. You have a way of writing compelling information that sparks much interest.
https://millikenconstructioninc.com/
https://millikenconstructioninc.com/
You are a very persuasive writer. I can see this in your article. You have a way of writing compelling information that sparks much interest.
https://findcosmeticsurgeons.net/
https://findcosmeticsurgeons.net/
I high appreciate this post. It’s hard to find the good from the bad sometimes, but I think you’ve nailed it!
https://safetytechnology.com
https://safetytechnology.com
I loved your post so much I became a fan of you, promise that you will continue to share such good and knowledgeable posts even further, we will be waiting for your post thank you.
https://bestpestcontrolservices.com.au
https://bestpestcontrolservices.com.au
It is wonderful to be here with everyone, I have a lot of knowledge from what you share, to say thank you, the information and knowledge here helps me a lot
https://bankncard.com/
https://bankncard.com/
Thank you so much for sharing this great blog.Very inspiring and helpful too.Hope you continue to share more of your ideas.I will definitely love to read.
https://bargainistafashionista.com/
https://bargainistafashionista.com/
Your information was very useful to me. That's exactly what I've been looking for
https://howtolose10poundsinaweek.com/
https://howtolose10poundsinaweek.com/
This is very educational content and written well for a change. It's nice to see that some people still understand how to write a quality post.!
https://tecsprint.com/
https://tecsprint.com/
Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking.
https://premiereretail.com/
https://premiereretail.com/
The post is written in very a good manner and it contains many useful information for me.
https://happygamer.com/
https://happygamer.com/
Now with coronavirus is really interesting to read things liek this on the internet when you stay at home
https://closetsphoenix.com/
https://closetsphoenix.com/
Wow very good post, please dont stop posting things like this because ie really enjoy this
https://caboplatinum.com/
https://caboplatinum.com/
Thank you so much for sharing this great blog.Very inspiring and helpful too.Hope you continue to share more of your ideas.I will definitely love to read.
https://zacjohnson.com/
https://zacjohnson.com/
Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking.
https://blogreign.com/
https://blogreign.com/
The post is written in very a good manner and it contains many useful information for me.
https://blogging.org/
https:https://blogging.org/
Very inspiring and helpful
https://blogninja.com/
https://blogninja.com/
This is very educational content and written well for a change. It's nice to see that some people still understand how to write a quality post.!
https://phoenixseogeek.com/
https://phoenixseogeek.com/
Thank you for such a well written article. It’s full of insightful information and entertaining descriptions. Your point of view is the best among many.
https://extremevaporizers.com/
https://extremevaporizers.com/
this is really nice to read..informative post is very good to read..thanks a lot!
https://usemybee.com/
https://usemybee.com/
Now with coronavirus is really interesting to read things liek this on the internet when you stay at home
https://spacnetwork.com/
https://spacnetwork.com/
You always stand by my side standard deviation calculator
Very nice article, I enjoyed reading your post, very nice share, I want to twit this to my followers. Thanks!. 먹튀검증
Very interesting discussion glad that I came across such informative post. Keep up the good work friend
https://pestcontrolcanberraarea.com.au
https://pestcontrolcanberraarea.com.au
I do not know what to say really what you share very well and useful to the community, I feel that it makes our community much more developed
https:https://emergencydental247.com/ https://emergencydental247.com/o/
It’s hard to find the good from the bad sometimes, but I think you’ve nailed it!
audigitalsolutions.com
audigitalsolutions.com
Great website and the content you shared is very informational and useful.
https://microjobs24.de https://microjobs24.de
It is wonderful to be here with everyone, I have a lot of knowledge from what you share, to say thank you, the information and https://audigitalsolutions.com/
https://audigitalsolutions.com/
Now with coronavirus is really interesting to read things liek this on the internet when you stay at home
https://plasticpalletsales.com
https://plasticpalletsales.com
I have bookmarked your blog, the articles are way better than other similar blogs.. thanks for a great blog!
https://megabonuscasino.nl/
https://megabonuscasino.nl/
I do not know what to say really what you share very well and useful to the community, I feel that it makes our community much more developed
https://vosairservices.com/
https://vosairservices.com/
Отправить комментарий
Приветствуются комментарии:Для остальных вопросов и обсуждений есть форум.