Re-using function inside jade

你说的曾经没有我的故事 提交于 2020-01-15 10:53:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!