8

我知道如何检查用户是否通过 PHP 登录,但是当事件发生时我需要做一些样式,我为此创建了一个单独的 JavaScript 文件。这是一个 Drupal 变量还是我也可以引用的东西?

4

4 回答 4

15

使用hook_init实现创建一个新的自定义模块。

function [YOUR_MODULE]_init()
{
    global $user;
    drupal_add_js(array('user_js_uid' => $user->uid), 'setting');
}

然后在您的 javascript 代码中,检查模块中定义的变量的值user_js_uid

if(Drupal.settings.user_js_uid == 0)
{
    // execute code for non logged in users
}
else
{
    // execute code for logged in users
}
于 2012-04-17T06:46:52.003 回答
14

如果您正在等待 DOM 准备好并使用标准生成的 Drupal CSS 类,您可以执行以下操作(使用 jQuery):

if( $( "body.not-logged-in" ).length )
{
    // user is not logged in
}
于 2013-05-30T06:42:04.420 回答
3

For Drupal 8 if you use Drupal.behaviors, you can access the user UID in settings:

(function($, Drupal, viewport, settings) {
  "use strict";
  Drupal.behaviors.ifCE = { //the name of our behavior
    attach: function (context, settings) {
    var userUID = settings.user.uid;
    //your code...
  }
})(jQuery, Drupal, ResponsiveBootstrapToolkit, drupalSettings);

So if the userUID === 0 then your user is not connected.

于 2017-03-13T08:25:58.530 回答
1

The "not-logged-in" class doesn't seem to exist in vanilla Drupal 8. But there's "user-logged-in" instead. Here's one line of CSS I'm using to hide the custom "Register" menu item if a user is logged in:

body.user-logged-in a[href="/user/register"] {display: none; }
于 2017-02-02T09:03:35.717 回答