11

Common Lisp 家伙有他们的CL-WHO,这使得 HTML 模板与“主要”语言集成,从而使任务更容易。对于那些不知道 CL-WHO 的人来说,它看起来像这样(示例来自 CL-WHO 的网页):

(with-html-output (*http-stream*)
(:table :border 0 :cellpadding 4
  (loop for i below 25 by 5
     do (htm
         (:tr :align "right"
          (loop for j from i below (+ i 5)
                do (htm
                    (:td :bgcolor (if (oddp j)
                                    "pink"
                                    "green")
                         (fmt "~@R" (1+ j))))))))))

你知道其他语言的类似库吗?我所知道的(模仿 CL-WHO)是Python 的Brevé。我对 Perl 风格特别感兴趣,但有趣的是其他语言如何处理将 HTML 集成到它们的语法中。

4

11 回答 11

12

对于CPAN产品,请查看以下内容(按字母顺序)...

使用提供的 CL-WHO 示例的表格部分(减去罗马数字和 s/background-color/color/ 在此处将代码压缩到屏幕宽度!)....


建造者

use Builder;
my $builder = Builder->new;
my $h = $builder->block( 'Builder::XML' );

$h->table( { border => 0, cellpadding => 4 }, sub {
   for ( my $i = 1; $i < 25; $i += 5 ) {
       $h->tr( { align => 'right' }, sub {
           for my $j (0..4) {
               $h->td( { color => $j % 2 ? 'pink' : 'green' }, $i + $j );
           }
       });
   } 
});

say $builder->render;


HTML::AsSubs

use HTML::AsSubs;

my $td = sub {
    my $i = shift;
    return map { 
        td( { color => $_ % 2 ? 'pink' : 'green' }, $i + $_ )
    } 0..4;
};

say table( { border => 0, cellpadding => 4 },
    map { 
        &tr( { align => 'right' }, $td->( $_ ) ) 
    } loop( below => 25, by => 5 )
)->as_HTML;


HTML::小

use HTML::Tiny;
my $h = HTML::Tiny->new;

my $td = sub {
    my $i = shift;
    return map { 
        $h->td( { 'color' => $_ % 2 ? 'pink' : 'green' }, $i + $_ )
    } 0..4;
};

say $h->table(
    { border => 0, cellpadding => 4 },
    [
        map { 
            $h->tr( { align => 'right' }, [ $td->( $_ ) ] )  
        } loop( below => 25, by => 5 )    
    ]
);


马尔卡普尔

use Markapl;

template 'MyTable' => sub {
    table ( border => 0, cellpadding => 4 ) {
       for ( my $i = 1; $i < 25; $i += 5 ) {
           row ( align => 'right' ) {
               for my $j ( 0.. 4 ) {
                   td ( color => $j % 2 ? 'pink' : 'green' ) { $i + $j }
               }
           }
       } 
    }
};

print main->render( 'MyTable' );


模板::声明

package MyTemplates;
use Template::Declare::Tags;
use base 'Template::Declare';

template 'MyTable' => sub {
    table {
        attr { border => 0, cellpadding => 4 };
        for ( my $i = 1; $i < 25; $i += 5 ) {
            row  {
                attr { align => 'right' };
                    for my $j ( 0..4 ) {
                        cell {
                            attr { color => $j % 2 ? 'pink' : 'green' } 
                            outs $i + $j;
                        }
                    }
            }
        } 
    }
};

package main;
use Template::Declare;
Template::Declare->init( roots => ['MyTemplates'] );
print Template::Declare->show( 'MyTable' );


XML::生成器

use XML::Generator;
my $x = XML::Generator->new( pretty => 2 );

my $td = sub {
    my $i = shift;
    return map { 
        $x->td( { 'color' => $_ % 2 ? 'pink' : 'green' }, $i + $_ )
    } 0..4;
};

say $x->table(
    { border => 0, cellpadding => 4 },
    map { 
        $x->tr( { align => 'right' }, $td->( $_ ) )  
    } loop( below => 25, by => 5 )    
);


以下可用于在 HTML::AsSubs / HTML::Tiny / XML::Generator 示例中生成“循环”....

sub loop {
    my ( %p ) = @_;
    my @list;

    for ( my $i = $p{start} || 1; $i < $p{below}; $i += $p{by} ) {
        push @list, $i;
    }

    return @list;
}
于 2009-03-23T09:21:02.710 回答
6

Perl 基金会当前资助的项目之一(Perl 6 的轻量级Web 框架)具有可工作的 Perl6 代码,该代码提供了类似的界面

use Tags;
say show {
    html {
        head { title { 'Tags Demo' } }
        body {
            outs "hi";
            ul :id<numberlist> {
                outs "A list from one to ten:";
                for 1..10 {
                    li :class<number>, { $_ }
                }
            }
        }
    }
}

浏览或克隆github上的当前代码。

于 2009-03-23T02:28:38.613 回答
5

Perl 的 CGI 模块支持这样的东西。

use CGI ':standard';
use Lisp::Fmt 

print header();

print table( { -border => 1, -cellpading => 4},
    loop({ below => 25, by=> 5}, sub {
        my $i = shift;
        tr( {-align => 'right'} ,
            loop({ from => $i, below $i + 5}, sub {
                my $j = shift;
                td({-bgcolor => ($oddp eq $j ? 'pink' : 'green')}
                    fmt("~@R", 1+$j);
            })
        )
    });

我试图让它保持 lispy,所以你必须自己实现一个 lispyloop函数。我并没有真正编写公共列表,所以我希望我正确理解了您的代码。

于 2009-03-22T20:51:03.293 回答
4

stan一种类似 s-expression 的语法,用于在纯 python 中表达 xml,来自Divmod 的 Nevow。我认为这是你想要的。链接教程中的一个示例:

t = T.table[
           T.tr[
               T.td[ "Name:" ],
               T.td[ original.name ]
           ],
           T.tr[
               T.td[ "Email:" ],
               T.td[T.a(href='mailto:%s' % original.email)[ original.email ] ]
           ],
           T.tr[
               T.td[ "Password:" ],
               T.td[ "******" ]
           ],
       ]
于 2009-03-22T23:57:23.063 回答
3

Perl 的标准CGI模块可以做类似的事情:

#!/usr/bin/perl

use strict;
use warnings;
use CGI qw/:standard/;

print 
    start_html("An example"),
    h1(
        {
            -align => "left",
            -class => "headerinfo",
        },
        'this is an example'
    ),
    "The CGI module has functions that add HTML:",
    ul( map li($_),
        ("start_html",
        "h1, h2, h3, etc.",
        "ol, ul, li",
        "ol, ul, li",
        "table, tr, th, td")
    ),
    "and many more.",
    end_html();

这会产生:

<!DOCTYPE html
        PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
<head>
<title>An example</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<h1 class="headerinfo" align="left">this is an example</h1>The CGI module has functions that add HTML:<ul><li>start_html</li> <li>h1, h2, h3, etc.</li> <li>ol, ul, li</li> <li>ol, ul, li</li> <li>table, tr, th, td</li></ul>and many more.
</body>
</html>

li 部分可以这样重写

print ol(map li($_), @list);

如果你有一个列表或数组。

于 2009-03-22T22:35:54.430 回答
3

Clojure

Clojure 中有许多受 CL-WHO 启发的 HTML 生成库(正如人们所料,Clojure 是一个 Lisp)。以下是使用Compojurecl-format附带的 HTML 库的方法:

(use 'compojure.html
     'com.infolace.format)

(html
 [:table {:border 0 :cellpadding 4}
  (map (fn [tds] [:tr {:align "right"} tds])
       (partition 5 (map (fn [num color]
                           [:td {:bgcolor color}
                            (cl-format nil "~@R" (inc num))])
                         (range 25)
                         (cycle ["green" "pink"]))))])

Compojure 的 HTML 库很好地利用了 Clojure 的文字哈希映射作为属性/值对,并且对标签使用文字向量而不是所有内容的列表有助于标签突出一点,并避免对宏魔术的一些需求。

partition将集合分解为若干个元素的组。 cycle生成一个无限重复的集合元素列表。这些加上rangemap帮助您避免显式循环和计数器变量。

于 2009-03-28T21:23:22.963 回答
1

JavaScript 就是这样。它如下所示:

T.div({ className: "content"},
      T.p("Some ", T.u("paragraph")),
      T.p("Another paragraph"))
于 2009-03-28T16:32:44.253 回答
1

哈斯克尔

Haskell 有一个与 CL-WHO 没有什么不同的 HTML 组合库。然而,惰性函数式编程方法确实导致了与 Common Lisp 中的循环设施大不相同的惯用迭代结构:

import Data.Char
import Data.List
import Text.Html
-- from http://fawcett.blogspot.com/2007/08/roman-numerals-in-haskell.html
import RomanNumerals

-- Simple roman numeral conversion; returns "" if it cannot convert.
rom :: Int -> String
rom r = let m = toRoman r
        in (map toUpper . maybe "" id) m

-- Group a list N elements at a time.
-- groupN 2 [1,2,3,4,5] == [[1,2],[3,4],[5]]
groupN n [] = []
groupN n xs = let (a, b) = splitAt n xs in a : (groupN n b)

pink = "pink" -- for convenience below; green is already covered by Text.Html

rom_table = table ! [border 0, cellpadding 4] << trs
    where
      -- a list of <tr> entries
      trs = map (rom_tr . map rom_td) rom_array

      -- generates a <tr> from a list of <td>s
      rom_tr tds = tr ! [align "right"] << tds

      -- generates a <td> given a numeral and a color
      rom_td (r, c) = td ! [bgcolor c] << r

      -- our 5 x 5 array (list x list) of numerals and colors
      rom_array = (groupN 5 . take 25) rom_colors

      -- a theoretically infinite list of pairs of roman numerals and colors
      -- (practically, though, the roman numeral library has limits!)
      rom_colors = zip (map rom [1..]) colors

      -- an infinite list of alternating green and pink colors
      colors = cycle [green, pink]

main = let s = prettyHtml rom_table 
       in putStrLn s

我应该注意 Text.Html 中还有一个小组合库,用于使用“above”和“beside”运算符来计算行/列跨度来组合表格,但是在应用属性来精确复制这个示例方面有点过于简单,并且我们不需要花哨的行和列拆分。

于 2010-07-22T21:20:44.837 回答
1

html-tags,一个鸡计划扩展。html-tags 生成 [X]HTML 或 SXML。

这是一个示例(使用循环扩展并考虑字符串输出):

(<table> border: 0 cellpadding: 4
  (string-intersperse
   (loop for i below 25 by 5
         collect
         (<tr> align: "right"
               (string-intersperse
                (loop for j from i below (+ i 5)
                      collect
                      (<td> bgcolor: (if (odd? j)
                                         "pink"
                                         "green")
                            (+ 1 j))))))))

我会添加指向循环和 html-utils 扩展(基于 html-tags 构建)的链接,但 stackoverflow 认为我是垃圾邮件发送者,并且只允许我发布最多两个链接。

于 2011-06-22T18:02:55.063 回答
0

Racket 的内置XML 库具有此功能。它能够从“X 表达式”生成 XML/HTML。例如:

#lang racket
(require xml)

(define my-name "XYZ")
(define my-list '("One" "Two" "Three"))
(define my-html
  `(html
     (head (title "Hello!")
           (meta ((charset "utf-8"))))
     (body (h1 "Hello!")
           (p "This is a paragraph.")

           ;; HTML attributes.
           (p ((id "some-id")
               (class "some-class"))
              "This is another paragraph.")
           (p "This is a link: " (a ((href "https://example.com")) "Example"))

           ;; Unquoting.
           (p "My name is: " ,my-name ".")
           (p ,(string-append "My name is: " my-name "."))  ; Same thing.

           (ul (li "One")
               (li "Two")
               (li "Three"))
           ;; Programatically generate the same list as above.
           (ul ,@(map (lambda (x)
                        `(li ,x))
                      my-list))

           ,(comment "This is a HTML comment."))))

(displayln (string-append "<!DOCTYPE html>"
                          (xexpr->string my-html)))
于 2021-02-19T20:17:14.407 回答
0

domonic是一个 python 库,它使用魔法方法和 dunders 来尝试和支持这种东西......

from domonic.html import *
mydom = html(body(h1('Hello, World!')))
print(f"{mydom}")

文档... https://domonic.readthedocs.io/packages/html.html

pip install domonic
于 2021-10-21T13:47:36.333 回答