问题
I have a inline script and code block repeated 2 times inside a .jade file and would like to:
- re-use it. (i mean DRY it and have just one block/function)
- escape the html like suggested here, right now I am using
!= linkExist('foo')
My idea was to use mixin
, but don't know how to. My code works as is, but would like to know how to write it better. Thought about codereview (because my code actually works and I just want to improve it) but the jade has not even a tag there yet, so I think SO might be better.
h1 Teachers
for result in object.teachers
- var linkExist = function(i){
- if (result[i] != 'undefined'){
- var html = ', follow on ' + i + ': <a href="' + result[i] + '" target="_blank">' + result[i].split("http://")[1] + '</a>';
- return html;
- };
- }
section
h3 #{result.Name}
p.inline #{result.Nick}
img(src=result.img)
p.small Location: #{result.Location}
p.small
| Web:
for webResult in result.Web
a(href=webResult,target='_blank') #{webResult.split('http://')[1]}
!= linkExist('Twitter')
!= linkExist('GitHub')
//now it repeats the code but for students
h1 Students
for result in object.students
- var linkExist = function(i){
//etc.......
回答1:
You should be able to use a mixin; if you pass result
as well, it should be pretty generic:
mixin linkExist(result, type)
if result[type] !== undefined
| , follow on #{type}: <a href="#{result[type]}">...</a>
//- use like this
for result in object.teachers
...
mixin linkExist(result, 'Twitter')
mixin linkExist(result, 'GitHub')
for result in object.students
...
mixin linkExist(result, 'Twitter')
mixin linkExist(result, 'GitHub')
来源:https://stackoverflow.com/questions/19927777/re-using-function-inside-jade