Mar 1, 2009

Latex on blogger using Google API

在 blogspot template 中插入如下代码
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.js"></script>
  <script>
   $(document).ready(function(){
    $(".latex").each(function(){
     $(this).html('<img src="http://chart.apis.google.com/chart?cht=tx&chl='+$(this).html()+'" alt="equation" />')
    });
   });
  </script>
对于 blogger template,第二个 script tag 内包含特殊字符,需要把它们转化一下。如果是写html,则没有这个问题

Latex 公式书写:
<pre class="latex">
   \sin(x)
  </pre>
注意因为 API 是以url形式发送,故必须满足 url 编码。+ 号用 %2B,空格用\quad

Remember that you must URL-encode any non-URL-safe characters used in your formula. You can find a URL-encoder here. The most common mistake is using + in a formula instead of %2B:
Not URL-EncodedURL-Encoded
a^2 + b^2 = c^2
cht=tx&chl=a^2+b^2=c^2
a^2 + b^2 = c^2
cht=tx&chl=a^2%2Bb^2=c^2


为了也能处理以前 lang=eq.latex,将下列代码加入 document.ready 内
$("pre[lang=eq.latex]").each(function(){
     $(this).html('<img alt="equation" src="http://chart.apis.google.com/chart?cht=tx&chl='+$(this).html()+'" />')
    });


代码例子
<html>
 <head>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.js"></script>
  <style>
   .latex { vertical-align: middle;} /*default styling for latex imgs */
   .bordered { border: 1px solid red;}
   .block { display: block; }
  </style>
  <script>
   $(document).ready(function(){
    $(".latex").each(function(){
     $(this).html('<img src="http://chart.apis.google.com/chart?cht=tx&chl='+$(this).html()+'" alt="equation" />')
    });
   });
  </script>
 </head>
 <body>
  Default look:
  <pre class="latex">
   \sin(x)
  </pre>
  how about an inlined, red bordered formula?
  <pre class="latex bordered">
   \sum_0^\infty \frac{x^n}{n!}
  </pre>
  Very nice! And if we give it the block class?
  <pre class="latex block">
   \int \int_{\mathbb{R}^2} \exp(-x^2 - y^2) dx dy
  </pre>
  See, it went on its own line. Magic!
 </body>
</html>

0 comments: