Google Translate APIを使って翻訳ボタンを作る

Google Translate API を利用した翻訳機能は Ver. 3.1.12 で廃止されました。
a-blog cms Ver.2.8.0に組み込みJSに翻訳機能がつきました。この機能を使うことで日本語を例えば英語に変換して別のテキストエリアに翻訳結果を自動入力するカスタマイズが可能になります。
まずは Google Translate API を使用するために以下の2つのステップが必要になります。
- API key の取得
- API key を CMS のプロパティ設定で登録する。
1. API key の取得

まずは、Google API Console にアクセスしてログインしてください。ログイン後、任意の名前でプロジェクトを作成します。 上の画像のように 1, 2 の手順でプロジェクトを新規作成できます。

左上のセレクトメニューをクリックし、先ほど作成したプロジェクトを選択します。

次は、サブカラムより「ライブラリ」という項目をクリックし、API ライブラリのページに移動します。そのページにて、Google Cloud Translation APIという項目を検索して有効化してください。


最後に「認証情報」をクリックして認証情報の設定画面に移動します。そこで新たに API key を作成します。今回はキーの制限は「なし」でも大丈夫です。ただしセキュリティ上、「IP アドレス」を指定し、アクセスできるIPアドレスを制限しておくことをオススメします。

この時発行される API key を覚えておきましょう。
2. API key を CMS のプロパティ設定で登録する。

プロパティ設定
あとは以下のように、js-translate
というクラスをボタンに付与します。そうすると、data-sourceで指定された要素からdata-targetに指定された要素に翻訳されたテキスト内容が自動で入力されます。
<button type="button" data-lang="en" data-source="翻訳元のセレクター" data-target="翻訳先のセレクター" class="js-translate">翻訳</button>
例えば、/themes/beginner/admin/entry/field.html に以下のコードを追記してください。翻訳ボタンをクリックするとカスタムフィールドにエントリーのタイトルが英語に翻訳されたものが自動入力されます。
<table class="acms-admin-table-admin-edit"> <tr> <th>英語版タイトル<i class="acms-admin-icon-tooltip js-acms-tooltip" data-acms-tooltip="英語版のタイトルを入力してください。"></i></th> <td> <div class="acms-admin-form-action"> <input type="text" name="title_en" value="{title_en}" class="acms-admin-form-width-full" id="entry-title-en" /> <span class="acms-admin-form-side-btn"> <button type="button" data-lang="en" data-source="#entry-title" data-target="#entry-title-en" class="acms-admin-btn js-translate">翻訳</button> </span> </div> <input type="hidden" name="field[]" value="title_en" /> </td> </tr> </table>